跟进我之前的问题(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的根目录中,它给出了一个错误:
可附加物业&#39;状态&#39;未在类型&#39; CarView&#39;
中找到
在我的MainWindow中,我使用ContentControl
:
<ContentControl
Content="{Binding CurrentCar}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type viewmodel:CarViewModel}">
<views:CarView />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
我的ViewModel:
[ImplementPropertyChanged]
public class CarViewModel
{
public Car Car { get; private set; }
public CarStatus Status
{
get
{
if (_sold) return CarStatus.Sold;
return CarStatus.NotSold;
}
}
}
答案 0 :(得分:1)
你的装订没有写好。而不是写views:CarView.Status="{Binding Status}"
,你应该只写Status="{Binding Status}"
答案 1 :(得分:0)
您的控件似乎与自身绑定 在CarView中查找状态。
您的控件CodeBehind中应该有一行代码,如:
this.DataContext = new ViewModelObjectWithStatusPropertyToBindFrom();
此致