使用 DataTemplate 的 ListBox 的 WPF 双向绑定 [英] WPF TwoWay Binding of ListBox using DataTemplate

查看:87
本文介绍了使用 DataTemplate 的 ListBox 的 WPF 双向绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何在绑定到列表时使 ListBox 可编辑<string>?

我正在尝试在名为ListStr"的列表对象和 ListBox WPF 控件之间设置两个绑定.此外,我希望这些项目是可编辑的,所以我添加了一个带有 TextBoxes 的 DataTemplate,希望它可以通过 TextBoxes 直接修改 ListStr 项目.

I'm trying to set a two-binding between a List named "ListStr" object and a ListBox WPF control. Besides I want the items to be editable, so I added a DataTemplate with TextBoxes expecting that it would modify the ListStr items straight away via TextBoxes.

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

But when I'm attempting to edit one of them, it doesn't work...

有什么想法吗?

PS:我已尝试添加 Mode=TwoWay 参数,但仍然无法正常工作

PS: I've tried to add the Mode=TwoWay parameter, but it's still not working

这是 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 x:Key="dtplItemTextContentListBoxEdit">
    <TextBox Text="{Binding Path=.}" Width="175" />
</DataTemplate>

推荐答案

使用 {Binding Path=.} 时双向绑定不起作用(对于 {Binding}).记住正在发生的事情.

Two way binding does not work when you use {Binding Path=.} (which is long for {Binding}). Keep in mind what is happening.

ListBox 被赋予一个对象列表,然后它为每个项目创建一个 ListBoxItem.然后将 ListBoxItemDataContext 设置为该对象.当你使用 {Binding} 时,你是说只使用 DataContext 中的对象.当您在 TextBox 中键入内容时,它会更新什么?它无法设置 DataContext 并且不知道对象来自哪里(因此它无法更新您的列表/数组).

The ListBox is given a list of objects, which it then creates one ListBoxItem for each item. The DataContext of the ListBoxItem is then set to that object. When you use {Binding}, you are saying to just use the object in the DataContext. When you type in the TextBox, what would it update? It can't set the DataContext and it has no idea where the object came from (so it can't update your list/array).

两种方式绑定起作用的地方是,当您绑定到该对象上的属性时.但不是当你绑定到对象本身时.

Where two way binding does work, is when you bind to a property on that object. But not when you bind to the object itself.

这篇关于使用 DataTemplate 的 ListBox 的 WPF 双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆