将按钮从用户控件绑定到视图模型未按预期工作



我有MainWindow.xaml和MainWindowViewModel,我在MainWindow.xam中有用户控制,我希望当用户单击用户控制按钮将此事件发送到MainWindowViewModel时,我有:

主窗口内我有:

<Controls:UserControl1 CloseBtn="{Binding CloseBtn}" ></Controls:UserControl1>

UserControl1.xaml:

<Button  Command="{Binding CloseBtn}" />

UserControl1.cs:

public static readonly DependencyProperty CloseProperty =
DependencyProperty.Register(
"CloseBtn",
typeof(ICommand),
typeof(UserControl1),
new PropertyMetadata(null));
public ICommand CloseBtn
{
get { return (ICommand)GetValue(CloseProperty); }
set { SetValue(CloseProperty, value); }
}

MainWindowViewModel.cs:

public ICommand CloseBtn { get; set; }
public MainWindowViewModel()
{
CloseBtn = new RelayCommand(o => BtnCloseSettings());
}
void BtnCloseSettings()
{
MessageBox.Show("test");
}

主窗口和视图模型已连接,但单击此按钮不会弹出"测试"消息框。

我错过了什么?

这里的问题是这一行:

<Button  Command="{Binding CloseBtn}" />

您已经在UserControl1中创建了一个依赖属性,并正确地将其与以下行绑定:

<Controls:UserControl1 CloseBtn="{Binding CloseBtn}" ></Controls:UserControl1>

但第一个绑定绑定到UserControl的DataContext的CloseBtn属性。它需要绑定到UserControl的CloseBtn依赖属性。要解决此问题,请首先为UserControl命名:

<UserControl x:Class="YourApp.UserControl1"
... etc ...
x:Name="_this">

然后将你的按钮命令绑定改为绑定:

<Button Command="{Binding CloseBtn, ElementName=_this}" />

或者,如评论中所述:

<Button Command="{Binding CloseBtn,
RelativeSource={RelativeSource AncestorType=UserControl}}" />

其中不需要分配UserControl的x:Name属性,从而避免创建未使用的专用字段。

最新更新