【问题标题】:Binding to an IValueConverter in Silverlight在 Silverlight 中绑定到 IValueConverter
【发布时间】:2012-04-06 05:28:03
【问题描述】:

我正在 Silverlight 中开发 IValueConverter。此值转换器需要遍历 MyOption 元素的集合并获得匹配项。 MyOption 值实际上来自数据库。我在 DataGrid 中使用这个转换器。因此,我不想每次都访问数据库。相反,我想访问数据库一次,然后将选项传递给转换器。为此,我想我会公开一个属性并将我的 MyOption 元素集合绑定到它,如下所示:

<converters:MyTypeConverter x:Key="myTypeConverter" UpdateTypes="{Binding Path=MyOptions}" />

...

<TextBlock Text="{Binding Path=OptionID, Converter={StaticResource myTypeConverter}}" />

然后我定义 MyTypeConverter,如下所示:

public class MyTypeConverter : UIElement, IValueConverter
{
  public ObservableCollection<MyOption> Options
  {
    get { return (ObservableCollection<MyOption>)GetValue(OptionsProperty); }
    set { SetValue(OptionsProperty, value); }
  }

  public static readonly DependencyProperty OptionsProperty =
    DependencyProperty.Register("Options",
      typeof(string), typeof(MyTypeConverter), null);

  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    string result = SomeObject.Convert(value, Options);
    return result;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return value;
  }
}

不幸的是,我似乎无法让它工作。这几乎就像我无法绑定到转换器。我收到一个编译时错误,上面写着:“System.Windows.UIElement 类型没有定义构造函数。”同时,我不知道如何将 MyOptions 传递给类型转换器,这样我就不会多次往返服务器。

【问题讨论】:

    标签: silverlight xaml


    【解决方案1】:

    这是转换器参数的来源。您需要将您的选项连同您的 OptionID 一起发送:

    <converters:MyTypeConverter x:Key="myTypeConverter" />
    ...
    <TextBlock Text="{Binding Path=OptionID, 
                      Converter={StaticResource myTypeConverter}, 
                      ConverterParameter={Binding Path=MyOptions}}" />
    

    类型转换器:

    public class MyTypeConverter : UIElement, IValueConverter
    {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
         var Options = parameter As ObservableCollection<MyOption>
         string result = SomeObject.Convert(value, Options);
         return result;
      }
    
      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
         return value;
      }
    }
    

    你会想要检查参数是否不为空,并且在你传递它之后包含一些东西,但你明白了......

    【讨论】:

    猜你喜欢
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 2013-04-10
    • 2013-11-15
    • 2011-02-10
    • 2012-01-25
    相关资源
    最近更新 更多