美文网首页.NET
WPF MVVM模式通过附加属性在ViewMode中获得View

WPF MVVM模式通过附加属性在ViewMode中获得View

作者: 丶PanPan | 来源:发表于2018-07-17 08:50 被阅读11次

    1.定义IViewModel接口

        public interface IViewModel
        {
            Window View { get; set; }
        }
    

    2.定义附加属性

        public class AttchedPropertys
        {
            public static bool GetGetView(DependencyObject obj)
            {
                return (bool)obj.GetValue(GetViewProperty);
            }
    
            public static void SetGetView(DependencyObject obj, bool value)
            {
                obj.SetValue(GetViewProperty, value);
            }
    
            // Using a DependencyProperty as the backing store for IsAutoBindEvent.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty GetViewProperty =
                DependencyProperty.RegisterAttached("GetView", typeof(bool), typeof(AttchedPropertys), new PropertyMetadata(false, OnPropertyChanged));
    
            private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                if (d is Window view)
                {
                    view.DataContextChanged += (s, en) =>
                    {
                        var vm = (IViewModel)view.DataContext;
                        vm.View = view;
                    };
                }
            }
        }
    

    3.ViewModel继承IViewModel接口

    public class AttachedPropertyViewModel : ObservableObject, IViewModel
        {
            public AttachedPropertyViewModel()
            {
                ClickCommand = new RelayCommand<object>(m =>
                {
                    var view = this.View;
                });
            }
    
            public ICommand ClickCommand { get; set; }
    
            public Window View { get; set; }
        }
    

    4.View XAML Code

    引入XAML NameSpace

    xmlns:vm="clr-namespace:WpfApp1.ViewModel"
    

    使用附加属性及设置Window DataContext

        vm:AttchedPropertys.GetView="True"
        DataContext="{Binding Source={StaticResource Locator}, Path=AttachedPropertyViewModel}"
    

    View XAML Code

    <Button
         x:Name="Button1"
         Command="{Binding ClickCommand}"
         Content="Tab1" />
    
    image.png

    Demo Github
    学习地址youtube

    相关文章

      网友评论

        本文标题:WPF MVVM模式通过附加属性在ViewMode中获得View

        本文链接:https://www.haomeiwen.com/subject/mjllpftx.html