将List <object>绑定到数据模板中的按钮的commandparameter

时间:2015-07-16 10:44:09

标签: wpf mvvm data-binding datatemplate

我想从列表中删除相应的对象,单击“删除”按钮 我已经分配了CommandParameter =“{Binding}”,它返回绑定到相应列表框项目的对象。

但我想在按钮单击上传递RuleConditions对象(ItemsSource =“{Binding RuleConditions}”)作为命令参数,然后从列表中删除对象,然后将其重新绑定到ListBox控件。

XAML代码:

<Window.Resources>
        <DataTemplate x:Key="UserTemplate" >
            <StackPanel Orientation="Horizontal" >
                <TextBox Text="{Binding Name}" Width="50"></TextBox>
                <TextBox Text="{Binding Age}" Width="50"></TextBox>
                <ComboBox ItemsSource="{Binding RuleType}"
                   Width="85" Height="20" Margin="5,5,5,5"/>
                <ComboBox ItemsSource="{Binding OperatorValues}"
                   Width="85" Height="20" Margin="5,5,5,5"/>
                <Button Content="Delete"  Margin="5,5,5,5" Command="{Binding  DataContext.ButtonCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}">                    
                </Button>

                <Button Content="Add"  Margin="5,5,5,5" />
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ListBox Name="lbUsers" ItemTemplate="{StaticResource UserTemplate}" ItemsSource="{Binding RuleConditions}"> 
        </ListBox>
    </Grid> 

请提前告知我任何不充分的信息,提前谢谢

1 个答案:

答案 0 :(得分:0)

你可以这样做

<ListBox Name="lbUsers" ItemTemplate="{StaticResource UserTemplate}" ItemsSource="{Binding RuleConditions}"
             SelectedItem="{Binding RuleCondition,Mode=TwoWay}"> 

在ViewModel中创建一个RuleCondition属性。 然后在DataTemplate做这样的

  <Button Content="Delete"  Margin="5,5,5,5" Command="{Binding  DataContext.ButtonCommand, ElementName=lbUsers}"/>

您需要做的只是在命令中您需要检查RuleConditions包含RuleCondition并从列表中删除RuleCondition

相关问题