我試圖找到兩個用戶控件之間進行通信的最佳方式。我有一個主要的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