在ViewModel中更改属性时,不会调用ValueConverter

时间:2012-01-26 20:34:32

标签: wpf

我需要根据ViewModel中的布尔属性将Window的光标更改为沙漏,为实现这一点,我已经定义了一个转换器,它将bool转换为Cursor,如下所示:

   [ValueConversion(typeof(bool), typeof(Cursors))]
   public class CursorExtensionConverter : IValueConverter
   {
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
         if (value != null && ((bool)value))
         {
            return Cursors.Wait;
         }
         return Cursors.Arrow;
      }

      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
         throw new NotImplementedException();
      }
   }

在XAML中,我有以下标记将Window.Cursor绑定到转换器

    <Window.Resources>
        <Converters:CursorExtensionConverter x:Key="cursorExtensionConverter"/>
    </Window.Resources>
    <Window.Cursor>
        <Binding Path="IsBusy" Converter="{StaticResource cursorExtensionConverter}"/>
    </Window.Cursor>

在ViewModel中,当我设置IsBusy = true时; Convert中的CursorExtensionConverter函数未被调用。为什么呢?

由于

1 个答案:

答案 0 :(得分:1)

问题是由于窗口的DataContext设置为ViewModel以及何时解析XAML的顺序。它还与我们在ViewModel实现中如何处理PropertyChanged事件有关。哪个我无法在这里粘贴。

我还没有弄明白,但在这个特殊情况下,在后面的代码中构建绑定可以解决问题:

Binding binding = new Binding();
binding.Source = viewmodel;
binding.Path = new PropertyPath("IsBusy");
binding.Converter = new CursorExtensionConverter();
SetBinding(CursorProperty, binding); 
相关问题