【问题标题】:wpf UserControl command button click bindingwpf UserControl命令按钮点击绑定
【发布时间】:2018-05-01 00:31:22
【问题描述】:

我有用户控制:

<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));

我在主窗口上添加了用户控件:

<local:Header AddClick="{Binding Path=AddUser_Click}" LableContent="Users"></local:Header>

并在 MainWindow.cs 上添加点击事件

private void AddUser_Click(object sender, RoutedEventArgs e)
{

}

问题是 Lable 正在填充,但没有调用单击按钮的命令。我做错了什么?

【问题讨论】:

    标签: wpf binding command


    【解决方案1】:

    你需要设置两件事

    1. 为 window.xaml 指定 DataContext 并为 AddClick 命令指定相关源,以便可以在 Window 上找到 AddUser_Click。

    更新您的 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 属性。

    1. 绑定时的所有依赖属性都尝试在 DataContext 中而不是方法中查找属性。因此,该命令应该是 window.cs 上 ICommand 类型的一个属性,并且应该在构造函数中为其提供一个方法。

    为了实现这一点,大多数人使用http://www.wpftutorial.net/delegatecommand.html。只需将其复制到一个新文件中。 在您的 MainWindow.xaml.cs 中,添加此

    AddUser_Click = new DelegateCommand(AddUserMethod);
    

    您现在可以在同一个文件中添加一个名为 AddUserMethod 的方法,只要您单击用户控件中的按钮,它就会被调用!!

    【讨论】:

    • 可以举个例子,拜托。
    猜你喜欢
    • 1970-01-01
    • 2013-09-16
    • 2015-06-07
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    相关资源
    最近更新 更多