我试图找到两个用户控件之间进行通信的最佳方式。我有一个主要的XAML窗口,其中包含两个用户控件,它们又包含各种控件。每个用户控件背后的代码只需将DataContext设置为与其关联的View Model。视图模型包含绑定到控件的对象。 我想要做的是在用户控件1中的列表框改变选择时捕获,新的选定项目显示在用户控件2的编辑框中。当我使用视图模型时,我无法声明依赖属性所以我想知道什么是可接受的方式来执行此操作? 我附上了一些基本的代码来展示我如何设置控件。WPF用户控件之间的通信
主窗口XAML
<Window x:Class="CommsTest.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CommsTest.View"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:UserControl1 />
<local:UserControl2 />
</Grid>
的UserControl1 XAML
<UserControl x:Class="CommsTest.View.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ComboBox Height="23" HorizontalAlignment="Left" Margin="50,110,0,0" Name="comboBox1" VerticalAlignment="Top" Width="199" ItemsSource="{Binding Combo1}" />
</Grid>
UserControl1ViewModel.cs
class UserControl1ViewModel
{
private ObservableCollection<string> combo1 = new ObservableCollection<string>();
public ObservableCollection<string> Combo1
{
get { return combo1; }
}
}
UserControl2.XAML
<UserControl x:Class="CommsTest.View.UserControl2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="63,84,0,0" Name="textBox1" VerticalAlignment="Top" Width="170" Text="{Binding Path=Text1}" />
</Grid>
UserControl2ViewModel.cs
class UserControl2ViewModel
{
private string text1;
public string Text1
{
get { return text1; }
set { text1 = value; }
}
}
我怎么UserControl2.Text1是UserControl2.Combo1的选择的价值? 谢谢
谢里登,谢谢你的回答,我认为这是一个非常整洁的解决方案。我只是在理解视图模型对象的实例化方面苦苦挣扎。在你的例子中,父视图模型创建子视图模型的实例,如果子视图模型是从父视图模型继承的(你没有说明这一点,但我假设这就是你的意思),不是这造成了问题。另外,我在后面的View代码中创建View模型的实例,以便我可以为它们设置DataContext。再次感谢。 – user2936676