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中
在这里插入图片描述

相关推荐

  1. 【Golang】Gin 框架多种类型函数

    2024-07-15 09:36:03       30 阅读
  2. Android视图

    2024-07-15 09:36:03       49 阅读
  3. 如果reactive数据没有双向

    2024-07-15 09:36:03       52 阅读
  4. 静态和动态介绍?

    2024-07-15 09:36:03       38 阅读
  5. 【Golang】 如何在 Gin 框架中多次参数

    2024-07-15 09:36:03       30 阅读
  6. IP地址与mac地址、解

    2024-07-15 09:36:03       22 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-15 09:36:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-15 09:36:03       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-15 09:36:03       58 阅读
  4. Python语言-面向对象

    2024-07-15 09:36:03       69 阅读

热门阅读

  1. Spring Boot中的安全配置与实现

    2024-07-15 09:36:03       20 阅读
  2. 设计模式--抽象工厂模式

    2024-07-15 09:36:03       23 阅读
  3. 【C++ 】类与对象 -- 纯虚函数与抽象类

    2024-07-15 09:36:03       22 阅读
  4. 设计模式--简单(抽象)工厂模式

    2024-07-15 09:36:03       24 阅读
  5. python中停止线程的方法

    2024-07-15 09:36:03       19 阅读
  6. 【前端】fis框架学习

    2024-07-15 09:36:03       19 阅读
  7. 根据vue学习react

    2024-07-15 09:36:03       17 阅读
  8. C语言指针常见陷阱及避免方法

    2024-07-15 09:36:03       28 阅读
  9. C# 使用正则解析html

    2024-07-15 09:36:03       21 阅读
  10. XML Schema 指示器

    2024-07-15 09:36:03       28 阅读
  11. 概率论原理精解【2】

    2024-07-15 09:36:03       25 阅读
  12. 刷题2路1线

    2024-07-15 09:36:03       21 阅读
  13. 面向对象编程的6大原则

    2024-07-15 09:36:03       23 阅读