【发布时间】:2014-12-21 17:11:13
【问题描述】:
我的 xaml(View) 中有 ListView,其 itemsSource 绑定到 Observable 集合。
我的视图:
<ListView x:Name="TestVariables"
ItemsSource="{Binding TestVariables}"
Grid.Row="1"
Grid.Column="1"
Grid.ColumnSpan="3">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Background="White" Width="350">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="175"/>
<ColumnDefinition Width="175"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0"
Grid.Column="0"
Text="{Binding Key}"/>
<TextBox Grid.Row="0"
Grid.Column="1"
Text="{Binding Value}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
问题:那么当我运行我的应用程序并更改我的 TextBox 值时,我如何在我的视图模型中获得一个仅具有这些更改的新集合?我想在我的代码中的某个地方使用那个新集合。换句话说,我如何通知我的视图模型这些更改?
例如,如果我运行这个,我会得到:23 岁, 性女性, 高度2
如果我将文本框更改为:24 岁, 性别男, 高度2
我想在我的 viewModel 中构建一个新集合:年龄 24, 性男性
这是我的 ViewModel:
公共类 MainViewModel : ViewModelBase { 公共 ObservableCollection TestVariables { get;放; }
public MainViewModel()
{
TestVariables= new ObservableCollection<TestVariable>
{
new TestVariable() {Key = "age", Value = 23},
new TestVariable() {Key = "sex", Value = "female"},
new TestVariable() {Key = "height", Value = 2}
};
}
}
TestVarible 类:
public class TestVariable
{
public string Key { get; set; }
public object Value { get; set;}
}
}
谢谢
【问题讨论】:
-
尝试将
Binding模式设置为TwoWay。类似ItemsSource="{Binding Path=TestVariables, Mode=TwoWay}". -
将您自己的事件处理程序附加到每个集合对象上的 PropertyChanged。使用 Viewmodel 上的集合更改事件来附加您的处理程序。当然 testvariable 必须实现 INotifyPropertyChanged。