![](/img/trans.png)
[英]In WPF is it possible to bind to a property of a property in my DataContext?
[英]Is it possible to bind the property of a datacontext to the property of another datacontext
我有一個用於定義顏色的控件中的類:
public class ColorModel : INotifyPropertyChanged {
public Color Color{ get { ... } set { ... } }
}
我也有一個類,希望用於定義兩種顏色的LinearGradient Brushes:
public class GradientModel : INotifyPropertyChanged {
public Color First{ get { ... } set { ... } }
public Color Last{ get { ... } set { ... } }
}
這兩個類均用作負責定義其各自值的控件的DataContext。
我希望能夠使用我定義的ColorModel來指示GradientModel的“第一”和“最后”顏色的值(使用兩個單獨的控件,每個控件都將ColorModel用作DataContext)。
我正在努力盡可能地堅持MVVM。
我該如何完成這項任務?
完成此操作的另一種方法可能是定義GradientModel
,如下所示:
public class GradientModel : INotifyPropertyChanged {
public ColorModel First{ get { ... } set { ... } }
public ColorModel Last{ get { ... } set { ... } }
}
也就是說,不要將屬性定義為Color
,而是將它們定義為ColorModel
。 然后在構造函數中,訂閱PropertyChanged
事件並相應地更新您的成員。
注意:您必須將綁定路徑從First
更新為First.Color
,依此類推。
我定義的ColorModel決定了GradientModel的“第一”和“最后”顏色的值
在ColorModel
實例內,訂閱GradientModel
的INotifyPropertyChanged
機制的實例。 然后,在訂閱操作方法中,只需檢測屬性Color
change事件,並在發生事件時提取其值並相應地更新First
和Last
的屬性。
根據規則, Binding
僅對DependencyProperty
的DependencyObject
起作用。
使ColorModel
和GradientModel
DependencyObject
。
創建一個MainViewModel
以便您可以設置Binding
。
public class MainViewModel { public ColorModel CM1 { get; set; } public ColorModel CM2 { get; set; } public GradientModel GM { get; set; } public MainViewModel() { CM1 = new ColorModel(); CM2 = new ColorModel(); GM = new GradientModel(); Binding b1 = new Binding("Color"); b1.Source = CM1; b1.Mode = BindingMode.OneWay; BindingOperations.SetBinding(GM, GradientModel.FirstProperty, b1); Binding b2 = new Binding("Color"); b2.Source = CM2; b2.Mode = BindingMode.OneWay; BindingOperations.SetBinding(GM, GradientModel.LastProperty, b2); } } <TextBox x:Name="Ctrl1" HorizontalAlignment="Left" Height="23" Margin="32,48,0,0" TextWrapping="Wrap" Text="{Binding CM1.Color}" VerticalAlignment="Top" Width="120"/> <TextBox x:Name="Ctrl2" HorizontalAlignment="Left" Height="23" Margin="32,103,0,0" TextWrapping="Wrap" Text="{Binding CM2.Color}" VerticalAlignment="Top" Width="120"/>
XAML(為了演示,我在虛擬機中使用了字符串類型而不是顏色類型。)
<TextBlock HorizontalAlignment="Left" Height="23" Margin="210,77,0,0" TextWrapping="Wrap" Text="{Binding GM.First}" VerticalAlignment="Top" Width="120" Background="#FFE8D7D7"/>
<TextBlock HorizontalAlignment="Left" Height="23" Margin="352,77,0,0" TextWrapping="Wrap" Text="{Binding GM.Last}" VerticalAlignment="Top" Width="120" Background="#FFECD7D7"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.