列表框DataTemplate选择时清除文本框值

时间:2014-05-27 12:43:59

标签: c# wpf data-binding

对于我的ListBox,我有DataTemplate

<DataTemplate x:Key="lbTemplate" DataType="{x:Type ListBoxItem}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="6*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="{Binding Naam, Mode=OneWay}" VerticalAlignment="Center" />
        <TextBox TextAlignment="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}},
            Path=IsSelected, Converter={StaticResource BoolToAlignment}}"
            Text="{Binding Path=Aantal, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, TargetNullValue=0}"
    </Grid>
</DataTemplate>

属性绑定到哪个:

public class menuItem
{
    public int? Aantal { get; set; }
    public string Naam { get; set; }
}

如果选择了相应的TextBox而不会失去对ListBoxItem属性的绑定,如何清除Aantal?值?

1 个答案:

答案 0 :(得分:3)

StyleDataTrigger

一起使用
<Style TargetType="TextBox" x:Key="tbStyle">
    <Setter Property="Text" >
        <Setter.Value>
            <Binding Path="Aantal" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" />
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}},
                            Path=IsSelected}" Value="True">
            <Setter Property="Text" Value="{x:Null}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

修改

在选择Aantal后重置(清除)绑定的ListBoxItem属性:

通过向IsSelected添加以下样式,将ListBoxItem.IsSelected标记添加到您的商品类,并将其绑定到ListBox属性:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="IsSelected" Value="{Binding IsSelected}" />
    </Style>
</ListBox.ItemContainerStyle>

然后在IsSelected setter中添加代码:if (value) { this.Aantal = ""; }