在Command中调用时,Tag属性为null

时间:2017-08-07 09:22:59

标签: c# wpf data-binding command

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有一个值。那么如何使用Tag获取Command的值?

以下是我用来检查Tag是否有某些内容的内容:

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

1 个答案:

答案 0 :(得分: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>

请注意,我使用OriginalSource的{​​{1}}属性。