首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF CommandParameter绑定问题

WPF CommandParameter绑定问题
EN

Stack Overflow用户
提问于 2008-11-02 21:21:20
回答 2查看 13.8K关注 0票数 5

我在理解命令参数绑定是如何工作的时候遇到了一些麻烦。

当我在调用InitializeComponent之前创建小部件类的一个实例时,它似乎工作得很好。对ExecuteCommand函数中参数(窗口小部件)的修改将被“应用”到_widget。这是我所期望的行为。

如果_widget的实例是在InitializeComponent之后创建的,我会在ExecuteCommand函数中得到e.Parameter的空引用异常。

为什么会这样呢?我如何在MVP模式下工作,在MVP模式中,绑定的对象可能会在视图创建后创建?

代码语言:javascript
复制
public partial class WidgetView : Window
{
    RoutedCommand _doSomethingCommand = new RoutedCommand();

    Widget _widget;

    public WidgetView()
    {
        _widget = new Widget();
        InitializeComponent();
        this.CommandBindings.Add(new CommandBinding(DoSomethingCommand, ExecuteCommand, CanExecuteCommand));
    }

    public Widget TestWidget
    {
        get { return _widget; }
        set { _widget = value; }
    }

    public RoutedCommand DoSomethingCommand
    {
        get { return _doSomethingCommand; }
    }

    private static void CanExecuteCommand(object sender, CanExecuteRoutedEventArgs e)
    {
        if (e.Parameter == null)
            e.CanExecute = true;
        else
        {
            e.CanExecute = ((Widget)e.Parameter).Count < 2;
        }
    }

    private static void ExecuteCommand(object sender, ExecutedRoutedEventArgs e)
    {
        ((Widget)e.Parameter).DoSomething();
    }
}



<Window x:Class="CommandParameterTest.WidgetView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WidgetView" Height="300" Width="300"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <StackPanel>
        <Button Name="_Button" Command="{Binding DoSomethingCommand}"
             CommandParameter="{Binding TestWidget}">Do Something</Button>
    </StackPanel>
</Window>


public class Widget
{
    public int Count = 0;
    public void DoSomething()
    {
        Count++;
    }
}
EN

回答 2

Stack Overflow用户

发布于 2008-11-02 22:37:35

InitializeCompenent处理与该文件相关联的xaml。正是在这个时间点,CommandParameter绑定首先被处理。如果你在InitializeCompenent之前初始化你的字段,那么你的属性不会为空。如果您在之后创建它,则它为null。

如果您想在InitializeCompenent之后创建小部件,那么您将需要使用依赖属性。依赖关系proeprty将引发一个通知,该通知将导致CommandParameter被更新,因此它不会为空。

下面是如何使TestWidget成为依赖属性的示例。

代码语言:javascript
复制
public static readonly DependencyProperty TestWidgetProperty =
    DependencyProperty.Register("TestWidget", typeof(Widget), typeof(Window1), new UIPropertyMetadata(null));
public Widget TestWidget
{
    get { return (Widget) GetValue(TestWidgetProperty); }
    set { SetValue(TestWidgetProperty, value); }
}
票数 4
EN

Stack Overflow用户

发布于 2008-12-22 06:00:24

即使使用dependency属性,您仍然需要调用CommandManager.InvalidateRequerySuggested来强制计算命令的CanExecute。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/257396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档