如何通过ModelItem向泛型列表添加项目.属性类

本文关键字:添加 项目 属性 列表 泛型 何通过 ModelItem | 更新日期: 2023-09-27 18:05:38

我正在尝试添加新项目到通用列表。在我的XAML应用程序中,我有两个文本框,我已经绑定到属性。

<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到泛型属性或在我添加项目到泛型列表的方式?

如何通过ModelItem向泛型列表添加项目.属性类

由于@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>