【问题标题】:Tag property is null when called in Command在命令中调用时标记属性为空
【发布时间】:2017-08-07 09:22:58
【问题描述】:

XAML

<UserControl.CommandBindings>
    <CommandBinding Command="{x:Static local:ReturnsUserControl.GetValueCommand}"
                    Executed="ExecutedGetValueCommand"
                    CanExecute="CanExecuteGetValueCommand" />
</UserControl.CommandBindings>
<TextBox x:Name="txtExchangeQuantity" />
<Button Content="Add"
        Tag="{Binding ProductBarcode}"
        Command="{x:Static local:ReturnsUserControl.GetValueCommand}"
        CommandParameter="{Binding Text, ElementName=txtExchangeQuantity}"/>

代码隐藏

public static RoutedCommand GetValueCommand = new RoutedCommand();
private void ExecutedGetValueCommand(object sender, ExecutedRoutedEventArgs e)
{
    Button b = (sender) as Button;
    MessageBox.Show(b.Tag.ToString());
}
private void CanExecuteGetValueCommand(object sender, CanExecuteRoutedEventArgs e)
    e.CanExecute = true;
}

当我单击该按钮时,我收到一个NullException,因为显然Tag 的值为空,但我确信Tag 有一个值。那么如何使用Command 获取Tag 的值?

这是我用来检查Tag是否有东西的:

private void SampleClick(object sender, RoutedEventArgs e)
{
    Button btnSelect = sender as Button;
    string barcode = btnSelect.Tag.ToString();
    MessageBox.Show(barcode);
}

【问题讨论】:

    标签: c# wpf data-binding command


    【解决方案1】:

    您确定ProductBarcode 绑定确实有效吗?以下示例代码当然有效。请参考。

    private void ExecutedGetValueCommand(object sender, ExecutedRoutedEventArgs e)
    {
        Button btn = e.OriginalSource as Button;
        MessageBox.Show(btn.Tag.ToString());
    }
    

    <UserControl>
        <UserControl.CommandBindings>
            <CommandBinding Command="{x:Static local:ReturnsUserControl.GetValueCommand}"
                        Executed="ExecutedGetValueCommand"
                        CanExecute="CanExecuteGetValueCommand" />
        </UserControl.CommandBindings>
        <StackPanel>
            <TextBox x:Name="txtExchangeQuantity" />
            <Button Content="Add"
                            Tag="tag..."
                            Command="{x:Static local:ReturnsUserControl.GetValueCommand}"
                            CommandParameter="{Binding Text, ElementName=txtExchangeQuantity}"/>
        </StackPanel>
    </UserControl>
    

    请注意,我使用ExecutedRoutedEventArgsOriginalSource 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 1970-01-01
      相关资源
      最近更新 更多