WPF MVVM模式通過附加屬性在ViewMode中獲得View

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

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容