在窗口中实现IValueConverter';s代码隐藏

本文关键字:代码 隐藏 窗口 实现 IValueConverter | 更新日期: 2023-09-27 18:20:31

我正试图为Window上的一些控件定义一个转换器。我(和大多数人)通常这样做的方式是在自己的类中定义转换器,在Window.Resources中实例化该类的实例,然后使用它。在这种特殊情况下,问题是转换器需要访问窗口的DataContext,所以我决定在窗口的代码后面实现它:

public partial class MyWindow : Window, IValueConverter
{
    public MyWindow()
    {
        InitializeComponent();
        // Other operations  
    }
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // Access the DataContext and return a value
        return new object();
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
       throw new NotImplementedException();
    }
}

问题是我现在不知道如何在XAML中使用它。显然,我不想实例化这个类的新实例,因为我会丢失数据上下文。我试过

"{Binding ElementName=someElement, Path=SomeProperty, Converter={Binding ElementName=myWindow}"

其中myWindow是此窗口的名称。我得到一个运行时错误说:

"A 'Binding' cannot be set on the 'Converter' property of type 'Binding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject."

有办法做到这一点吗?感谢您的帮助。

在窗口中实现IValueConverter';s代码隐藏

这种特殊情况下的问题是转换器需要访问窗口的DataContext,所以我决定在后面的窗口代码中实现它

一种选择是使IValueConverter成为自己的类,并像往常一样在XAML中创建一个实例。如果将转换器设为DependencyObject,则可以为UIElement添加依赖项属性,并将Window(myWindow)绑定到该属性。这将允许转换器访问Window(通过其属性),以便获取DataContext。

在这种设计中,转换器可以在绑定中正常引用。

我认为MultiValueConverter可以解决您的问题:http://msdn.microsoft.com/en-us/library/system.windows.data.imultivalueconverter.aspx.在您的情况下,除了SomeProperty之外,您可以将窗口的DataContext传递给转换器,并执行任何您想要的操作。