【问题标题】:How to bind to a WPF dependency property to window?如何将 WPF 依赖属性绑定到窗口?
【发布时间】:2012-03-22 20:12:48
【问题描述】:

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

依赖属性:

  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 中定义了资源。

在xml中:

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

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

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

【问题讨论】:

  • 试试这个Command:WindowBehaviors.IsOpen="{binding Isopen,Mode=TwoWay}" 也许你的绑定值不正确。 o 显示为小写。
  • 不,这不是问题。我不能在资源定义之前绑定任何东西,例如对于标题,我必须在资源定义之后放置:
  • Isopen 是 myViewModel 的属性吗?
  • yes.Isopen 是 myViewModel 的属性

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    在您的情况下,作为静态资源的数据上下文应该可以工作:

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

    其实这和ebattulga建议的一样,只是XAML方式(没有代码后面)。

    【讨论】:

    • 谢谢,但我想绑定到窗口的属性而不是网格的孩子!我应该在这里写什么?!!! &lt;!-- the code with the binding goß into here --&gt;
    【解决方案3】:
        public MainWindow()
                {
                    InitializeComponent();
    
    // DO THIS
                    this.DataContext = Resources["myVieModel"];
    
                }
    

    【讨论】:

    • 谢谢。我会试一试,但我不想写后面的代码!
    • 它不起作用,它应该有一个简单的解决方案。怎么了?
    猜你喜欢
    • 1970-01-01
    • 2020-12-22
    • 2023-03-26
    • 2012-11-08
    • 2018-01-23
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多