【问题标题】:How can i add bindings to window in xaml to properties of class that jas been created as a resouse int this same window(xam)l?如何将绑定到 xaml 中的窗口添加到作为资源创建的类的属性中?
【发布时间】:2016-06-06 02:38:11
【问题描述】:

我有一个在窗口 xaml 文件中创建的类,并且在我想将此窗口的某些属性(我的情况是 DialogResult 属性)绑定到我创建的类的属性之后。

<Window x:Class="Galery.RegistrationWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
    xmlns:local="clr-namespace:Galery"
    Name="Reg"

    local:DialogCloser.DialogResult="{Binding Source={StaticResource UVM}, Path=DialogResult}"
    Title="Image Gallery 1.0 - Registration"
    Height="700" Width="400" WindowStartupLocation="CenterOwner">

<Window.Resources> 
    <local:RegisterWindowViewModel x:Key="RegViewModel"/>
    <local:RegisterValidationConverter x:Key="RegValid"/>
    <local:UsersViewModel x:Key="UVM"/>
    <local:ParameterConverter x:Key="paramConverter"/>
</Window.Resources>

在第 8 行出现错误 local:DialogCloser.DialogResult="{Binding Source={StaticResource UVM}, Path=DialogResult}"

我认为这是因为我正在使用的类尚未创建。

在 Window.Resources 中创建类后,如何将绑定添加到我的窗口,ro 甚至可以通过这种方式吗?

我希望我的解释清楚, 将非常感谢您的帮助。

【问题讨论】:

    标签: wpf


    【解决方案1】:

    您遇到问题的原因是您没有正确使用 MVVM。查看您的代码,我假设您已经意识到 DialogResult 无法绑定,并且您已经阅读了Joe White's article,其中他展示了如何使用附加属性将 DialogResult 绑定到视图模型。真正的问题是您在 Resources 块中声明视图模型:

    <Window.Resources> 
        <local:RegisterWindowViewModel x:Key="RegViewModel"/> <----- BAD!
        <local:RegisterValidationConverter x:Key="RegValid"/>
        <local:UsersViewModel x:Key="UVM"/>                   <----- BAD!
        <local:ParameterConverter x:Key="paramConverter"/>
    </Window.Resources>
    

    在 MVVM 中,您永远不会这样做,原因您刚刚发现。您应该创建视图模型的层次结构,然后将您的视图绑定到这些视图模型。资源块仅适用于与视图相关的元素,不适用于视图模型。

    如果您确实坚持将 Window 属性绑定到资源块中的对象,那么可以使用样式设置器来完成,例如:

    <Window.Resources>
        <local:MyClass x:Key="myClass"/>
    </Window.Resources>
    
    <Window.Style>
        <Style TargetType="{x:Type Window}" BasedOn="{StaticResource {x:Type Window}}">
            <Setter Property="Title" Value="{Binding Source={StaticResource myClass}, Path=MyStringProperty}" />
        </Style>
    </Window.Style>
    

    但同样,这仅适用于窗口依赖属性,不适用于附加属性,因为您绑定到的 Window 属性(即 DialogResult)不支持更改通知,因此更新不会发生在您的方向希望他们这样做。

    【讨论】:

      猜你喜欢
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 2011-05-30
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      相关资源
      最近更新 更多