C# 选择其他ListViewItem时更改DataContext
我构建了一个由ListView和带有几个文本框的面板组成的界面。为了在选择另一个ListViewItem时更改这些文本框中的上下文,我捕获了SelectionChange事件,以相应地更改文本框的DataContext。大概是这样的:C# 选择其他ListViewItem时更改DataContext,c#,.net,wpf,wpf-controls,binding,C#,.net,Wpf,Wpf Controls,Binding,我构建了一个由ListView和带有几个文本框的面板组成的界面。为了在选择另一个ListViewItem时更改这些文本框中的上下文,我捕获了SelectionChange事件,以相应地更改文本框的DataContext。大概是这样的: void customersList_SelectItem(object sender, SelectionChangedEventArgs e) { Customer customer = (Customer)customersList.Selected;
void customersList_SelectItem(object sender, SelectionChangedEventArgs e)
{
Customer customer = (Customer)customersList.Selected;
if (customer != null)
{
addressField.DataContext = customer;
phoneField.DataContext = customer;
mobileField.DataContext = customer;
webField.DataContext = customer;
emailField.DataContext = customer;
faxField.DataContext = customer;
...
}
}
现在,我想知道,这是最好的方法吗?看起来有点勉强,但我想不出更好的了。如果文本框都包含在一个包含元素中(例如网格),那么您可以只设置网格元素的DataContext。这会更干净
更好的方法是使用XAML绑定和,并且该代码可以在XAML中声明性地实现。如果文本框都包含在包含元素(例如网格)中,那么您可以只设置网格元素的DataContext。这会更干净
更好的方法是使用XAML绑定和,并且该代码可以在XAML中声明性地实现。将dependent controls DataContext属性绑定到ListBox的SelectedItem属性 或者,如果它们位于容器控件中,则最好设置其数据上下文一次,并让子控件继承它。类似于
<StackPanel DataContext="{Binding ElementName=ListBoxName, Path=SelectedItem}">
<!--- dependent controls -->
</StackPanel>
将dependent controls DataContext属性绑定到ListBox的SelectedItem属性 或者,如果它们位于容器控件中,则最好设置其数据上下文一次,并让子控件继承它。类似于
<StackPanel DataContext="{Binding ElementName=ListBoxName, Path=SelectedItem}">
<!--- dependent controls -->
</StackPanel>
您也可以将WPF中的与CollectionView结合使用:
<Window ... xmlns:local="...">
<Window.DataContext>
<local:MyViewModel ... />
</Window.DataContext>
<Window.Resources>
<CollectionViewSource x:Key="ItemsView" Source="{Binding Path=Items}" />
<Window.Resources>
<ListView ItemsSource="{Binding Source={StaticResource ItemsView}}">
...
</ListView>
<Grid DataContext="{Binding Source={StaticResource ItemsView}, Path=/}">
...
</Grid>
</Window>
...
...
要快速解释此设置,请执行以下操作:
- 窗口的datacontext设置为视图模型的实例
- CollectionViewSource创建为资源,并使用视图模型公开的集合作为其源
- listview的ItemsSource直接绑定到CollectionView(由CollectionViewSource公开)
- 网格(将包含表单元素)通过绑定到CollectionView的CurrentItem;每次在列表视图中选择一个项目时,网格的datacontext都会自动设置为当前选定的项目
<Window ... xmlns:local="...">
<Window.DataContext>
<local:MyViewModel ... />
</Window.DataContext>
<Window.Resources>
<CollectionViewSource x:Key="ItemsView" Source="{Binding Path=Items}" />
<Window.Resources>
<ListView ItemsSource="{Binding Source={StaticResource ItemsView}}">
...
</ListView>
<Grid DataContext="{Binding Source={StaticResource ItemsView}, Path=/}">
...
</Grid>
</Window>
...
...
要快速解释此设置,请执行以下操作:
- 窗口的datacontext设置为视图模型的实例
- CollectionViewSource创建为资源,并使用视图模型公开的集合作为其源
- listview的ItemsSource直接绑定到CollectionView(由CollectionViewSource公开)
- 网格(将包含表单元素)通过绑定到CollectionView的CurrentItem;每次在列表视图中选择一个项目时,网格的datacontext都会自动设置为当前选定的项目