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

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Caliburn.Micro是一套基于XAML的MVVM模式的开发框架,它是一个小巧而强大的框架。在Caliburn.Micro中,只需要按照约定将View的名字加上后缀ViewModel,就是它的ViewModel的名字,例如MainPage和MainPageViewModel。Caliburn.Micro会自动将ViewModel绑定到View的DataContext,并且如果ViewModel的属性名和控件的名称相同,它会自动进行绑定MVVM模式是一种用于开发WPF应用程序的架构模式,它将应用程序分为三个部分:Model、View和ViewModel。ViewModel负责处理View与Model之间的交互,以及将Model的数据呈现给View。MVVM模式的目标是编写优雅、可测试、可维护和可扩展的表示层代码,而Caliburn.Micro努力超越简单的MVVM实现,使开发变得更加容易。 在MVVM框架中,ViewModel通常需要实现INotifyPropertyChanged接口,以便在ViewModel的属性更改时能够自动发出事件通知View。在Caliburn.Micro中,ViewModel通常可以继承自PropertyChangedBase或Screen,这两个类都实现了INotifyPropertyChanged接口。如果继承自Screen,ViewModel可以像窗口一样进行激活、关闭等操作。 综上所述,Caliburn.Micro是一个基于XAML的MVVM框架,它使开发WPF应用程序变得更加简单和高效。它提供了自动绑定ViewModel到View的功能,同时也支持INotifyPropertyChanged接口,使ViewModel能够与View进行双向通信。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [C# WPF MVVM开发框架Caliburn.Micro入门介绍①](https://blog.csdn.net/zls365365/article/details/121711023)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [WPF MVVM框架Caliburn.Micro(一)简介](https://blog.csdn.net/Accidentabird/article/details/130192466)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值