我正在尝试为我的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."
有没有办法做到这一点?任何帮助表示赞赏。