如何将WPF依赖属性绑定到窗口?

时间:2012-03-05 10:41:21

标签: data-binding binding mvvm mvvm-light mvvm-toolkit

我创建了一个依赖项属性来关闭视图模型中的视图,

的DependencyProperty:

  public static class WindowBehaviors 
  {      
     public static readonly DependencyProperty IsOpenProperty =
              DependencyProperty.RegisterAttached("IsOpen"
             , typeof(bool),
             typeof(WindowBehaviors),
             new UIPropertyMetadata(false, IsOpenChanged));

    private static void IsOpenChanged(DependencyObject   obj,DependencyPropertyChangedEventArgs args)
    {
        Window window = Window.GetWindow(obj);

        if (window != null && ((bool)args.NewValue))
            window.Close();
    }


    public static bool GetIsOpen(Window target)
    {
        return (bool)target.GetValue(IsOpenProperty);
    }

    public static void SetIsOpen(Window target, bool value)
    {
        target.SetValue(IsOpenProperty, value);
    }
}

并在我的xaml中使用它:

<window
...
Command:WindowBehaviors.IsOpen="True">

它工作正常,但是当我想将它绑定到viewModel中的属性时,它不起作用,我想,它不起作用,因为我稍后在xaml中定义资源。

xaml中的

 <Window.Resources>
     <VVM:myVieModel x:Key="myVieModel"/>
 </Window.Resources>

我不知道该怎么办,我应该把它放在哪里:

Command:WindowBehaviors.IsOpen="{binding Isopen}"

3 个答案:

答案 0 :(得分:0)

    public MainWindow()
            {
                InitializeComponent();

// DO THIS
                this.DataContext = Resources["myVieModel"];

            }

答案 1 :(得分:0)

您需要绑定绑定所在范围的数据上下文。通常,这在您的XAML中相当高,通常是表单或控件中的第一个元素。

在您的情况下,数据上下文是一个静态资源,以下应该有效:

<grid DataContext="{StaticResource myVieModel}">
    <!-- the code with the binding goß into here -->
</grid>

实际上这与ebattulga建议的相同,只是XAML方式(后面没有代码)。

答案 2 :(得分:0)

感谢您的帮助,我修好了,这是我的解决方案, 我曾经使用MVVMToolkit,但现在我正在使用MVVMlight,正如你在MVVMLight中所知,我们只是在App.xaml.so中定义应用程序资源一次我们可以简单地绑定所有窗口的属性,希望这可以帮助一些拥有相同功能的人问题!!

的App.xaml

  <Application.Resources>
    <!--Global View Model Locator-->
    <vm:ViewModelLocator x:Key="Locator"
                         d:IsDataSource="True" />
  </Application.Resources>

并在窗口(视图)

DataContext="{Binding DefaultSpecItemVM, Source={StaticResource Locator}}"

它完美无缺。:D