【发布时间】:2013-07-01 17:10:30
【问题描述】:
我正在尝试为我的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."
有没有办法做到这一点?任何帮助表示赞赏。
【问题讨论】:
-
这里并不完全清楚——“需要访问 Window 的 DataContext”是什么意思?你的意思是你需要转换“DataContext.SomeProperty”吗?
-
没有。在
Convert和ConvertBack方法中,我需要访问窗口的DataContext。 -
当您将 ValueConverter 声明为资源时,您可以在对象上设置属性。您可以在 ValueConverter 上创建一个 DataContext 属性并进行设置。您可能必须使 ValueConverter 从 DependencyObject 继承,并且该属性可能需要是 DependencyProperty 才能执行此操作。
-
让我问另一种方式。你要绑定什么属性(是在这个窗口中,还是在一个单独的类中),你需要 DataContext 做什么?
标签: c# wpf xaml ivalueconverter