C#与静态资源绑定

时间:2015-01-19 16:35:43

标签: c# wpf mvvm

我需要设置控件的背景颜色,具体取决于标尺的打孔。所以,我正在尝试使用转换器来做到这一点。

在我的XAML中:

<TextBox Background="{Binding Converter={StaticResource BackgroundConverter}, ConverterParameter='UserName'}">

在我的转换器中,我找到了“UserName”的规则。但我使用整个绑定对象:

    object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null)
        {

            var person = (value as PersonBase).Person;
            if (person.state == editing)
                return GetRulesFor(parameter);
            else
                return Brushes.Silver;

它在第一次显示屏幕时有效,但我需要在用户编辑表单,取消等时更新这些属性。

如何设置我的绑定?

1 个答案:

答案 0 :(得分:0)

您可以在viewmodel中创建一个新属性并将其命名为State,然后返回person.state。当您更改person对象的状态时,只需调用OnPropertyChanged(“State”)。

public class YourViewModel : INotifyPropertyChanged
{
   // ... your code here
   public StateObjectType State
   {
       get {return person.state;}
   }

   // when you modify the person state just call OnPropertyChanged("State")
}

在您的视图中绑定文本框

<TextBox Background="{Binding State,Converter={StaticResource BackgroundConverter}, ConverterParameter='UserName'}">

这将使您的代码有效。

相关问题