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" />