WPF MVVM框架 Caliburn.Micro的Action绑定

WPF MVVM框架 Caliburn.Micro的Action绑定

  1. 通过命名约定来绑定Action
    View
<Window x:Class="WpfApp1.Views.AboutView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" WindowStartupLocation="CenterScreen" SizeToContent="WidthAndHeight"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:cal="http://www.caliburnproject.org"
        xmlns:conv="clr-namespace:WpfApp1.Converters"
        Title="About"  MinHeight="800" MinWidth="800" WindowStyle="SingleBorderWindow">

    <Grid>
    <Button Name="OK" Width="100" Height="80" Content="Click"/>
    </Grid>
</Window>

ViewModel


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Caliburn.Micro;
using WpfApp1.Models;

namespace WpfApp1.ViewModels
{
    public class AboutViewModel
    {
        public void Ok()
        {
             MessageBox.Show("Test");
        }
    }
}

点击View中的按钮时,可以把Clicked事件的处理函数导航到ViewModel中的OK方法中,其原因是命名规则遵守了Caliburn.Micro的约定,即View中的Button名称叫OK,ViewModel中有一个OK的方法。

  1. 通过Message.Attach来设置Event Handler
    View
<Window x:Class="WpfApp1.Views.AboutView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" WindowStartupLocation="CenterScreen" SizeToContent="WidthAndHeight"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:cal="http://www.caliburnproject.org"
        xmlns:conv="clr-namespace:WpfApp1.Converters"
        Title="About"  MinHeight="800" MinWidth="800" WindowStyle="SingleBorderWindow">
    <Grid>
        <Button cal:Message.Attach="OK" Width="100" Height="80" Content="Click"/>
    </Grid>
</Window>

ViewModel部分同上
就其原因是Caliburn.Micro内部有维护一个消息触发器,xaml中的写法相当于注册到了消息中心,当用户点击按钮时,消息中心会匹配到对应的ViewModel中同名的函数作为Handler

下面用一个完整的Demo展示,如何绑定到更复杂的事件、如何传参数
View

<Window x:Class="WpfApp1.Views.AboutView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" WindowStartupLocation="CenterScreen" SizeToContent="WidthAndHeight"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:cal="http://www.caliburnproject.org"
        xmlns:conv="clr-namespace:WpfApp1.Converters"
        Title="About"  MinHeight="800" MinWidth="800" WindowStyle="SingleBorderWindow">

    <Window.Resources>
        <conv:Color2SolidBrushConverter x:Key="colorConverter"/>

        <DataTemplate x:Key="combItem" DataType="{x:Type ComboBoxItem}">
            <StackPanel Orientation="Horizontal" Width="100"  Height="20">
                <Rectangle Width="20" Height="20" Fill="{Binding Color,Converter={StaticResource colorConverter}}"/>
                <TextBlock Text="{Binding Name}" Margin="5,0,0,0"/>
            </StackPanel>
        </DataTemplate>

    </Window.Resources>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200"/>
            <ColumnDefinition Width="600"/>
        </Grid.ColumnDefinitions>
        <Grid Grid.Column="0">
            <ComboBox Name="cmb" ItemsSource="{Binding Colors}" SelectedItem="{Binding SelectedColor}" Width="100" Height="28" ItemTemplate="{StaticResource combItem}"
                      cal:Message.Attach="[Event SelectionChanged] = [Action OnSelectedColorChanged($eventArgs)]"/>
        </Grid>
        <Grid Grid.Column="1">
            <Rectangle Fill="{Binding SelectedColor.Color,Converter={StaticResource colorConverter}}"/>
        </Grid>

    </Grid>
</Window>

ViewModel

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.ObjectModel;
using System.Windows.Controls;
using Caliburn.Micro;
using WpfApp1.Models;

namespace WpfApp1.ViewModels
{
    public class AboutViewModel:Screen
    {
        private ColorModel _selectedColor;
        public ObservableCollection<ColorModel> Colors { get; set; }


        public ColorModel SelectedColor
        {
            get => _selectedColor;
            set
            {
                _selectedColor = value;
                NotifyOfPropertyChange(nameof(SelectedColor));
            }
        }


        public void OnSelectedColorChanged(SelectionChangedEventArgs e)
        { 

        }

        public AboutViewModel()
        {
            Colors=new ObservableCollection<ColorModel>();
            Colors.Add(new ColorModel("Red","Red"));
            Colors.Add(new ColorModel("Green","Green"));
            Colors.Add(new ColorModel("Blue","Blue"));
            Colors.Add(new ColorModel("White","White"));
        }
    }
}

Model

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Caliburn.Micro;

namespace WpfApp1.Models
{
    public class ColorModel : Screen
    {
        private string _color;
        private string _name;

        public ColorModel(string color, string name)
        {
            _color = color;
            _name = name;
        }

        public string Color
        {
            get => _color;
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    _color = value;
                    NotifyOfPropertyChange(nameof(Color));
                }
            }
        }

        public string Name
        {
            get => _name;
            set
            {
                if (!string.IsNullOrEmpty(_name))
                {
                    _name = value;
                    NotifyOfPropertyChange(nameof(Name));
                }
            }
        }
    }
}

Converter

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace WpfApp1.Converters
{
    public class Color2SolidBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                if (value.ToString() == "Red")
                {
                    return new SolidColorBrush(Colors.Red);
                }else if(value.ToString() == "Green")
                {
                    return new SolidColorBrush(Colors.Green);
                }else if (value.ToString() == "Blue")
                {
                    return new SolidColorBrush(Colors.Blue);
                }
                else
                {
                    return new SolidColorBrush(Colors.Black);
                }
            }
            return default;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return default;
        }
    }
}

效果:
左边的Combobox变化时,把对应的颜色填充到右边的Rectangle中
在这里插入图片描述

上一篇:MySQL 聚簇索引和非聚簇索引有什么区别?


下一篇:PMG:基于渐进式多粒度拼图块训练的细粒度视觉分类——【ECCV_2020_论文学习】