数据模板中的 WPF 文本框双向绑定不更新源

问题描述 投票:0回答:0

我创建了一个 ListBox,在其中我指定了一个带有 Grid 的 DataTemplate 和其中的两个元素(TextBlock 和 TextBox)。 ListBox 中的源是 ObservableCollection。一切都显示正常,但是当我尝试更改 TextBox 中的值时,绑定源没有改变。

我按照这个解决方案来解决问题: https://stackoverflow.com/a/31110958/20863772

但是没用。文本框现在不显示任何内容(即使集合已正确填充并包含元素)

这里是查看代码:

<ListBox ItemsSource="{Binding Path=PlugboardPermutations, UpdateSourceTrigger=PropertyChanged}"
         BorderThickness="0"
         ScrollViewer.HorizontalScrollBarVisibility="Disabled"
         xmlns:system='clr-namespace:System;assembly=mscorlib'
         AlternationCount="{x:Static system:Int32.MaxValue}"
         SelectedIndex="{Binding ListSelectedIndex}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="IsSelected" Value="True"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
    
    <ListBox.Style>
        <Style TargetType="ListBox">
            <Setter Property="ItemContainerStyle">
                <Setter.Value>
                    <Style TargetType="ListBoxItem">
                        <Setter Property="Focusable" Value="False"/>
                    </Style>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.Style>
    
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid Margin="5">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>

                <TextBlock Grid.Column="0" Width="30" TextAlignment="Right" 
                           Text="{Binding Path=(ItemsControl.AlternationIndex),
                      RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}},
                      StringFormat=' {0}: ', Mode=OneWay}"/>

                <TextBox Grid.Column="1" Width="30" DataContext="{Binding Path=Content, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Tag="{Binding}"/>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

有人能帮忙吗?

wpf data-binding textbox datatemplate
© www.soinside.com 2019 - 2024. All rights reserved.