【问题标题】:Binding a Command inside a Style在样式中绑定命令
【发布时间】:2012-03-18 08:57:21
【问题描述】:

我目前正在开发一个使用 MVVM 的 WPF 应用程序。我有一个 ListBox,其样式设置为使其像 RadioButtonList 一样显示,如下所示:

<Style x:Key="RadioButtonList" TargetType="{x:Type ListBox}">
    <Setter Property="BorderBrush" Value="{x:Null}" />
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="{x:Type ListBoxItem}" >
                <Setter Property="Margin" Value="2" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ListBoxItem}">
                            <Border Background="Transparent">
                                <RadioButton Focusable="False" IsHitTestVisible="False" IsChecked="{TemplateBinding IsSelected}" Content="{Binding Path=DisplayName}" Command="{Binding ElementName=ShippingWindow, Path=DataContext.ShipOtherMethodSelected}">
                                </RadioButton>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Setter.Value>
    </Setter>
</Style>

<ListBox Name="lbShipOtherMethodOptions" Style="{StaticResource RadioButtonList}" ItemsSource="{Binding Path=ShipOtherMethodOptions}" Margin="13,74,366,282" />

我要做的是将命令绑定到 RadioButton,以便在进行选择时触发事件。我的视图模型中有以下代码,但我似乎无法启动它:

    private ICommand shipOtherMethodSelected;
    public ICommand ShipOtherMethodSelected
    {
        get
        {
            return shipOtherMethodSelected ??
                   (shipOtherMethodSelected = new RelayCommand(param => ShipOpenItems(), param => true));
        }
    }

    private void ShipOpenItems()
    {
        MessageBox.Show("GOT HERE");
    }

我对 WPF 和 MVVM 还很陌生,所以我可能遗漏了一些明显的东西。谁能指出我正确的方向?

编辑: 根据 jberger 的建议,我输入了一些我尝试过但不起作用的代码。在该部分设置断点没有被触发,消息框也没有出现。

编辑 2: 因此,在检查了发送方的 DataContext 之后,发现它指向的是我将 RadioButton 绑定到的对象,而不是我的视图模型。我更新了上面的代码(在我的窗口中添加了一个 x:Name 并更新了 Command 绑定),现在我让事件在最初绑定时触发,但是当我选择一个值时它不会触发。看来我们现在真的很接近了。

【问题讨论】:

  • 你没有在你的 xaml 中绑定 ShipOtherMethodSelected
  • 对不起,我试过了,但在复制/粘贴我的代码之前我必须还原。我会解决的
  • 如果您删除 Focusable="False" IsHitTestVisible="False" 会发生什么?如果您挂钩Click 事件,点击时会触发吗?
  • 删除 Focusable 和 IsHitTestVisible 并没有给我的结果带来任何变化。然而,挂钩 Click 事件确实触发了。我似乎无法让它绑定到我的 ICommand 似乎很奇怪。
  • Click 事件处理程序中使用调试器浏览sender,并检查DataContext 以确保它包含ShipOtherMethodSelected

标签: wpf binding mvvm command


【解决方案1】:

ShipOtherMethodSelected 位于您的(主)ShippingVM 而不是您的ShipItemVM,因此您需要设置

Command="{Binding ElementName=ShippingWindow, Path=DataContext.ShipOtherMethodSelected}"

其中ShippingWindowListBoxItem“上方”元素的x:Name

另外,Focusable="False" IsHitTestVisible="False" 拒绝点击。删除设置器。

【讨论】:

    猜你喜欢
    • 2018-11-20
    • 2016-01-14
    • 2014-01-20
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多