从用户控件到视图模型的绑定按钮无法正常工作

问题描述 投票:0回答:1

[我有MainWindow.xaml和MainWindowViewModel,我在MainWindow.xaml中有User Conterol,我希望当用户单击用户控件按钮以将此事件发送到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");
}

MainWindow和viewmodel已连接,但是单击此按钮不会弹出“ test”消息框。

我想念什么?

wpf mvvm user-controls
1个回答
0
投票

问题是此行:

<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}" />
© www.soinside.com 2019 - 2024. All rights reserved.