2017-08-07 2 views
1

namens XAMLTag-Eigenschaft ist null, wenn in Command

<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}"/> 

-Code-behind

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; 
} 

Wenn ich die Schaltfläche geklickt, erhalte ich einen NullException weil anscheinend die Tag ‚s-Wert ist null, aber ich bin mir sicher, dass der Tag einen Wert hat. Wie kann ich den Tag Wert mit Command bekommen?

Hier ist, was ich verwendet, um zu überprüfen, ob die Tag etwas hat:

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

Antwort

1

Sind Sie sicher, dass die ProductBarcode Bindung tatsächlich funktioniert? Der folgende Beispielcode funktioniert sicherlich. Bitte nehmen Sie Bezug darauf.

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> 

Bitte beachte, dass ich die OriginalSource Eigenschaft des ExecutedRoutedEventArgs verwenden.

Verwandte Themen