【问题标题】:How can I bind to the window my binding is in?如何绑定到我的绑定所在的窗口?
【发布时间】:2016-10-11 04:59:35
【问题描述】:

我有一个依赖于定义它的窗口的数据绑定。

尝试像这样创建绑定:

<Binding Source="{RelativeSource Self}"/>

导致错误。

我希望绑定解析到窗口本身...我该如何完成?

这已被标记为几个问题的重复,但是其中描述的方法是我在这里尝试的方法,它不起作用。

我正在使用我编写的 MultiConverter,它需要两个绑定 - 一个绑定到布尔值,一个绑定到窗口:

<MultiBinding Converter="{c:MyMultiConverter}">
    <MultiBinding.ConverterParameter>
        <sys:Int32>0</sys:Int32>
    </MultiBinding.ConverterParameter>
    <!--This binding works fine-->
    <Binding Path="MyBooleanProperty" Source="{x:Static MyPropertySource}"/>

    <!--This binding results in an error - 'Value cannot be null.'-->
    <Binding Source="{RelativeSource Self}"/>
</MultiBinding>

这是转换器转换功能的要点:

public object Convert(
    object[ ] values, Type targetType,
    object parameter, CultureInfo culture ) {
    int
        //Get the monitor number the window is currently on...
        Monitor = Screen.AllScreens.ToList( ).IndexOf( ( values[1] as Window ).Screen( ) ), 
        //[0] : If true, multiply by 2; else by 1. Add Parameter.
        Index =  ( Monitor * ( ( bool ) values[0] ? 2 : 1 ) ) + ( int )parameter;
    return MyProject.MyList[Index];
}

Window.Screen( ) 只是一个简单的扩展方法,它返回窗口所在的屏幕。

调试显示尝试解析values[1] as Window 会导致null...

【问题讨论】:

标签: c# wpf xaml data-binding


【解决方案1】:
{Binding RelativeSource={RelativeSource AncestorType=Window}}

【讨论】:

  • 这在 MultiBinding 中看起来如何?
  • &lt;Binding RelativeSource="{RelativeSource AncestorType=Window}"/&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多