我有usercontrol:
<UserControl x:Class="MyApp.Header"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="40" d:DesignWidth="300" DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}">
<Grid>
<Label Content="{Binding LableContent, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"></Label>
<Button Command="{Binding Path=AddClick, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}">
<Image Source="{StaticResource addImage}" Height="20"/>
</Button>
</Grid>
</UserControl>
usercontoror中的依赖属性:
public string LableContent
{
get { return (string)GetValue(LableContentProperty); }
set { SetValue(LableContentProperty, value); }
}
public static readonly DependencyProperty LableContentProperty =
DependencyProperty.Register("LableContent", typeof(string), typeof(Header));
public ICommand AddClick
{
get { return (ICommand)GetValue(AddClickProperty); }
set { SetValue(AddClickProperty, value); }
}
public static readonly DependencyProperty AddClickProperty =
DependencyProperty.Register("AddClick", typeof(ICommand), typeof(Header));
我在mainwindow上添加了usercontrol:
<local:Header AddClick="{Binding Path=AddUser_Click}" LableContent="Users"></local:Header>
在MainWindow.cs上添加click事件
private void AddUser_Click(object sender, RoutedEventArgs e)
{
}
问题是Lable正在填充,但是没有调用命令单击按钮。我做错了什么?
答案 0 :(得分:0)
您需要设置两件事
将Window.xaml AddClick绑定更新为
<local:Header AddClick="{Binding Path=DataContext.AddUser_Click, RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor}}" LableContent="Users"/>
并将Window.xaml的DataContext设置为Window.xaml.cs,方法是将其添加到MainWindow构造函数
this.DataContext = this;
执行上述步骤将确保可以正确找到AddUser_Click属性。
为了实现这一点,大多数人使用http://www.wpftutorial.net/delegatecommand.html。只需将其复制到新文件即可。 在MainWindow.xaml.cs中,添加此
AddUser_Click = new DelegateCommand(AddUserMethod);
您现在可以在同一个文件中添加一个名为AddUserMethod的方法,只要您点击User Control !!中的按钮就会调用它!