【发布时间】:2016-01-09 15:54:24
【问题描述】:
跟进我之前的问题 (Change brushes based on ViewModel property)
在我的 UserControl 中,我有一个 DependencyObject。我想将该对象绑定到我的ViewModel 的属性。在本例中为CarViewModel,属性名称为Status,并返回一个枚举值。
public partial class CarView : UserControl
{
public CarStatus Status
{
get { return (CarStatus)GetValue(CarStatusProperty); }
set { SetValue(CarStatusProperty, value); }
}
public static readonly DependencyProperty CarStatusProperty =
DependencyProperty.Register("Status", typeof(CarStatus), typeof(CarView), new PropertyMetadata(OnStatusChanged));
private static void OnStatusChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
var control = (CarView)obj;
control.LoadThemeResources((CarStatus)e.NewValue == CarStatus.Sold);
}
public void LoadThemeResources(bool isSold)
{
// change some brushes
}
}
<UserControl x:Class="MySolution.Views.CarView"
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"
xmlns:views="clr-MySolution.Views"
mc:Ignorable="d"
views:CarView.Status="{Binding Status}">
<UserControl.Resources>
</UserControl.Resources>
<Grid>
<TextBlock Text="{Binding Brand}"FontSize="22" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
<UserControl
我需要在哪里指定这个绑定?在 UserControl 的根目录中,它给出了一个错误:
在“CarView”类型中找不到可附加属性“Status”
在我的 MainWindow 中,我使用 ContentControl 绑定 CarView:
<ContentControl
Content="{Binding CurrentCar}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type viewmodel:CarViewModel}">
<views:CarView />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
我的视图模型:
[ImplementPropertyChanged]
public class CarViewModel
{
public Car Car { get; private set; }
public CarStatus Status
{
get
{
if (_sold) return CarStatus.Sold;
return CarStatus.NotSold;
}
}
}
【问题讨论】:
-
我对 MVVM 很放心,但我看不出你在用 ContentControl 做什么。在 ContentControl 内部有一个 DataTemplate 仅适用于 CarView(DataType 属性用于选择而不是实例化),并且与 CurrentCar 属性的绑定应该有一个 DataContext 对象——我仍然不知道它是如何提供的。如果您想为您的 ViewModel 提供 XAML:
。但我更喜欢用 C# 来做:更短,有时你必须在 CS 中处理 VM。
标签: c# wpf data-binding user-controls dependencyobject