绑定到 List时如何使 ListBox 可编辑?
编辑:基本问题是将列表绑定到ListBox(或任何其他控件)。所以我正在编辑问题。
我将字符串列表绑定到列表框,如下所示。但是,当我更改文本框的内容时,它并没有更改源列表中的字符串。为什么?
public partial class MainWindow : Window
{
List<string> _nameList = null;
public List<string> NameList
{
get
{
if (_nameList == null)
{
_nameList = new List<string>();
}
return _nameList;
}
set
{
_nameList = value;
}
}
public MainWindow()
{
NameList.Add("test1");
NameList.Add("test2");
InitializeComponent();
}
和 XAML
<ListBox Grid.Row="0" Grid.Column="0" DataContext="{Binding ElementName=main}" ItemsSource="{Binding NameList}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding .,Mode=OneWayToSource , UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Edit: The basic problem is binding a List to ListBox(or any other control). So I am editing the question.
I bound a list of string to a ListBox as below. However when I change the contents of the textbox it is not changing the string in the source list.Why?
public partial class MainWindow : Window
{
List<string> _nameList = null;
public List<string> NameList
{
get
{
if (_nameList == null)
{
_nameList = new List<string>();
}
return _nameList;
}
set
{
_nameList = value;
}
}
public MainWindow()
{
NameList.Add("test1");
NameList.Add("test2");
InitializeComponent();
}
And the XAML
<ListBox Grid.Row="0" Grid.Column="0" DataContext="{Binding ElementName=main}" ItemsSource="{Binding NameList}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding .,Mode=OneWayToSource , UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每个
ListBoxItem
的DataContext
是字符串本身,因此绑定的路径为空 (.
)。TwoWay
和OneWayToSource
绑定需要路径,因为您不能只替换当前的DataContext
。因此,您需要将字符串包装在一个将字符串公开为属性的对象中:将字符串公开为
StringItem
列表:并绑定到
Value
属性:请注意
StringItem
还需要实现INotifyPropertyChanged
以便自动更新绑定。您还应该将列表公开为ObservableCollection
而不是List
The
DataContext
of eachListBoxItem
is the string itself, so the path of your binding is empty (.
).TwoWay
andOneWayToSource
bindings require a path, since you can't just replace the currentDataContext
. So you need to wrap your string in an object that exposes the string as a property:Expose the strings as a list of
StringItem
:And bind to the
Value
property:Note that
StringItem
will also need to implementINotifyPropertyChanged
so that bindings are automatically updated. You should also expose the list as anObservableCollection<T>
rather than aList<T>
可能有帮助吗?
May be it helsp?
您可以使用项目控件和文本框创建 DataGridTemplateColumn.CellEditingTemplate 来编辑项目
you can create a DataGridTemplateColumn.CellEditingTemplate with an itemscontrol and textboxes to edit your items
如果我没有误解你的问题,那么实现起来非常容易。看:
If I didn't misunderstand your question, it is pretty easy to implement. Look: