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);
}
答案 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}}属性。