[英]How to add item to generic list through ModelItem.Properties class?
我正在尝试将新项目添加到通用列表。 在我的XAML应用程序中,我有2个文本框,并且已绑定到属性。
<TextBox Text="{Binding Path=ModelItem.ReplaceThis, Mode=TwoWay}"></TextBox>
<TextBox Text="{Binding Path=ModelItem.ReplaceWithThat, Mode=TwoWay}"></TextBox>
单击按钮时,我想将两个字段的值添加到将在绑定到通用列表属性的ListBox中显示的通用列表中
<Button Name ="btnReplaceAdd" Content="Add" Width="50" Click="btnReplaceAdd_Click"></Button>
<ListBox ItemsSource="{Binding Path=ModelItem.ReplaceItems, Mode=OneWay}"/>
在后面的代码中访问属性,我有以下代码。
private void btnReplaceAdd_Click(object sender, RoutedEventArgs e)
{
var _with = this.ModelItem.Properties["ReplaceThis"].Value;
var _what = this.ModelItem.Properties["ReplaceWithThat"].Value;
var foo = new List<RenameReplace>();
var bar = new RenameReplace() { Rwht = _what.ToString(), Rwth = _with.ToString() };
foo.Add(bar);
this.ModelItem.Properties["ReplaceItems"].SetValue(foo);
this.ModelItem.Properties["ReplaceThis"].SetValue("");
this.ModelItem.Properties["ReplaceWithThat"].SetValue("");
}
一旦方法执行完成,而不是看到我传递的值,我就会在列表框中看到MyProject.RenameReplace
。
我将XAML ListBox绑定到通用属性的方式还是将项目添加到通用列表的方式是我的问题吗?
通过@fmunkert的评论指出使用ItemTemplate
能够解决此问题
必须替换后面代码中的下4行
var foo = new List<RenameReplace>();
var bar = new RenameReplace() { Rwht = _what.ToString(), Rwth = _with.ToString() };
foo.Add(bar);
this.ModelItem.Properties["ReplaceItems"].SetValue(foo);
有了这个
var bar = new RenameReplace() { Rwht = _what, Rwth = _with };
this.ModelItem.Properties["ReplaceItems"].Collection.Add(bar);
现在必须更改XAML
<ListBox ItemsSource="{Binding Path=ModelItem.ReplaceItems, Mode=OneWay}"/>
为了能够并排显示两个项目。
<ListBox ItemsSource="{Binding Path=ModelItem.ReplaceItems, Mode=OneWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Path=ModelItem.Rwht}" />
<TextBlock Grid.Column="1" Text="{Binding Path=ModelItem.Rwth}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.