使用CommandParameter时,TextBox的Text属性返回null

时间:2017-08-07 07:49:43

标签: wpf data-binding

我设法创建了Command,如下所示:

代码隐藏

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

XAML

<UserControl.CommandBindings>
    <CommandBinding Command="{x:Static local:ReturnsUserControl.GetValueCommand}"
                    Executed="ExecutedGetValueCommand"
                    CanExecute="CanExecuteGetValueCommand" />
</UserControl.CommandBindings>

<ListView>
    <ListView.View>
        <GridView>
            <GridViewColumn>
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal"
                                    VerticalAlignment="Center"
                                    HorizontalAlignment="Center">
                            <TextBlock Text="{Binding ProductDescription}"/>
                         </StackPanel>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn>
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal"
                                    VerticalAlignment="Center"
                                    HorizontalAlignment="Center">
                            <TextBox x:Name="txtExchangeQuantity"
                                     Tag="{Binding ProductBarcode}"/>
                            <Button Content="Add"
                                    Tag="{Binding ProductBarcode}"
                                    Command="{x:Static local:ReturnsUserControl.GetValueCommand}"
                                     CommandParameter="{Binding Text,ElementName=txtExchangeQuantity}"/>
                         </StackPanel>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

当我点击按钮时,CommandParameter总是返回null,即使我在文本框中放了一些东西,我也确定该命令正常工作,因为Custom Command Executed显示了。

我想在这里实现的是获取与TextBox Tag Button值的Tag的值>(相同的条形码),因为TextBoxButton都有多个实例,Tag是唯一可以配对的实例。

1 个答案:

答案 0 :(得分:1)

正如我们在评论中所说的那样,您应该寻找ExecutedRoutedEventArgs.Parameter而不是检查事件处理程序中的sender