WPF使用DataTemplate实现ListBox的双向绑定

3

可能是重复问题:
如何在绑定到List<string>时使ListBox可编辑?

我正在尝试在一个名为“ListStr”的列表对象和一个ListBox WPF控件之间设置双向绑定。 此外,我希望这些项是可编辑的,所以我添加了一个DataTemplate和TextBoxes,期望通过TextBoxes直接修改ListStr项。

但是当我尝试编辑其中一个时,它不起作用......

有什么想法吗?

附注:我已经尝试添加Mode=TwoWay参数,但仍然不起作用。

这是XAML代码:

<ListBox ItemsSource="{Binding Path=ListStr}" Style="{DynamicResource ResourceKey=stlItemTextContentListBoxEdit}" />

这里是样式代码:

<Style x:Key="stlItemTextContentListBoxEdit" TargetType="{x:Type ListBox}">
<Setter Property="Background" Value="#FF0F2592" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Foreground" Value="White" />
<Setter Property="Height" Value="150" />
<Setter Property="Width" Value="200" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="ItemTemplate" Value="{DynamicResource ResourceKey=dtplItemTextContentListBoxEdit}" /></Style>

而且DataTemplate:

<DataTemplate x:Key="dtplItemTextContentListBoxEdit">
    <TextBox Text="{Binding Path=.}" Width="175" />
</DataTemplate>
2个回答

8
当您使用{Binding Path=.}(即{Binding}的长格式)时,双向绑定不起作用。请记住正在发生的事情。 ListBox被赋予一个对象列表,然后为每个项目创建一个ListBoxItemListBoxItemDataContext然后设置为该对象。当您使用{Binding}时,您是在说只需使用DataContext中的对象。当您在文本框中输入时,它会更新什么?它无法设置DataContext,也不知道对象来自哪里(因此无法更新列表/数组)。
双向绑定有效的地方是当您绑定到该对象上的属性时。但是,当您将绑定绑定到对象本身时,则不起作用。

我不确定: 每个ListBoxItem的DataContext是什么? - Pamplemousse
我的问题非常简单:我想修改一个与 ListBox 绑定的 List<string>,该怎么做? - Pamplemousse
1
你需要一个带有setter的项,这样绑定才能更改你的数据,创建一个具有属性的类,并使用它来代替字符串并绑定到该属性。 - ZSH
@Pamplemousse - 你不能像那样使用 ListBox 修改 List<string>。请参考 ZSH 的答案了解如何实现。 - CodeNaked

3
    public class ViewModel
{
    ObservableCollection<TextItem> _listStr = new ObservableCollection<TextItem> { new TextItem("a"), new TextItem("b"), new TextItem("c") };

    public ObservableCollection<TextItem> ListStr
    {
        get  { return _listStr; }  // Add observable and propertyChanged here also if needed
    }
}

public class TextItem : NotificationObject // (NotificationObject from Prism you can just implement INotifyPropertyChanged)
{
    public TextItem(string text)
    {
        Text = text;
    }

    private string _text;
    public string Text
    {
        get { return _text; }
        set
        {
            if (_text != value)
            {
                _text = value;
                RaisePropertyChanged(() => Text);
            }
        }
    }
}


xaml:

 <DataTemplate>
    <TextBox Text="{Binding Text}" Width="175" />
 </DataTemplate>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接