【问题标题】:Command Is Not Firing From VIew命令未从 VIew 触发
【发布时间】:2013-07-01 01:51:21
【问题描述】:

我有一个使用 XAML 的 Windows 商店应用程序,其中我有一个类型的绑定:

DelegateCommand<DomainObject>

我正在尝试绑定 DomainObject 的列表,如下所示。注意项目模板中的按钮,触发 StartCommand:

<ItemsControl
    x:Name="MyList"
    ItemsSource="{Binding Path=Items}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Style="{StaticResource Para}">
                <Image>
                    <Image.Source>
                        <BitmapImage UriSource="{Binding Path=Image}" />
                    </Image.Source>
                </Image>

                <TextBlock Text="{Binding Path=Name}" Width="300" />

                <Button Content="Start"
                    Command="{Binding Path=StartCommand}"
                    CommandParameter="{Binding}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

在视图模型中,我有以下内容:

public DelegateCommand<DomainObject> StartCommand
{
    get { return _startCommand; }
    set
    {
        _startCommand = value;
                //method I use to fire the property changed event
        this.NotifyPropertyChanged("StartCommand");
    }
}

我通过以下方式实例化命令实例:

StartCommand = new DelegateCommand<DomainObject>(StartSession);

但是,当单击按钮时,它永远不会触发命令...我在 StartSession 中的断点没有被命中。我哪里出错了?是我如何设置命令或参数吗?我想不通。另请注意,ItemsControl 中的项目绑定到 DomainObject 的实例,因此我想将其作为 CommandParameter 传递,这就是为什么我认为我搞砸了...

【问题讨论】:

    标签: c# .net xaml windows-8 windows-store-apps


    【解决方案1】:

    这不起作用的原因是ItemTemplate 中的DataContext。行:

    <Button Content="Start"
            Command="{Binding Path=StartCommand}"
            CommandParameter="{Binding}"/>
    

    将绑定到DomainObject 类中的StartCommand 属性,而不是您的视图模型。一定要绑定到正确的 DataContext(你的 ItemsControl,而不是你的 ItemContainer 绑定的那个),需要做一个小的调整:

    <Button Content="Start"
            Command="{Binding Path=DataContext.StartCommand, 
                              RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
            CommandParameter="{Binding}"/>
    

    这样,WPF 绑定将找到 ItemsControl 类型的祖先并绑定到 DataContext.StartCommand 属性(假设 DataContext 是您的视图模型)。

    【讨论】:

    • 谢谢,这是有道理的。我收到一条错误消息,提示 Windows 商店应用程序不支持 AncestorTYpe...
    • 在这种情况下,您可以尝试将RelativeSource 部分替换为ElementName=MyList
    • 谢谢,ElementName 是解决方案。
    猜你喜欢
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2019-10-09
    • 2016-10-22
    • 1970-01-01
    相关资源
    最近更新 更多