我正在尝试为我的 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."
有办法实现吗?感谢您的帮助。
最佳答案
The problem in this particular case is that the converter needs to access the window's DataContext,so I decided to implement it in the window's code behind
一种选择是使 IValueConverter
成为自己的类,并像往常一样在 XAML 中创建一个实例。如果将转换器设为 DependencyObject
,则可以为 UIElement
添加依赖属性,并将 Window (myWindow
) 绑定(bind)到该属性。这将允许转换器访问 Window(通过它的属性)以获取 DataContext。
在此设计中,转换器可以在绑定(bind)中正常引用。
关于c# - 在 Window 的代码后面实现 IValueConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17409963/