未加载WPF资源

本文关键字:资源 WPF 加载 | 更新日期: 2023-09-27 18:28:29

好吧,我有一点XAML似乎不想工作。它的意思是显示"MainWindowViewModel.Property"的值,但它并没有这样做。

首先,代码:

主窗口.xaml:

<Window x:Class="MyNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyNamespace"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:MainWindowViewModel x:Key="ViewModel"/>
    </Window.Resources>
    <Grid>
        <Label Content="{Binding Property, Source={StaticResource ViewModel}}"/>
    </Grid>
</Window>

主窗口.xaml.cs:

namespace MyNamespace
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

MainWindowViewModel.cs

namespace MyNamespace
{
    public class MainWindowViewModel
    {
        public string Property = "test";
    }
}

这对我来说似乎很正确,但它在运行时不起作用,设计师给了我一个神秘的错误:

PropertyPath
 Property expected

绑定中的"Property"周围。有什么想法吗?

谢谢!

未加载WPF资源

这里的问题是MainWindowViewModelProperty成员是字段而不是属性,并且WPF只支持绑定到属性。所以你的视图模型至少应该是这样的:

namespace MyNamespace
{
    public class MainWindowViewModel
    {
        public MainWindowViewModel()
        {
            Property = "test";
        }
        public string Property { get; set; }
    }
}

如果您计划在视图模型的整个生命周期中更改值,那么您也可以考虑实现INotifyPropertyChanged

而不是

<Window.Resources>
    <local:MainWindowViewModel x:Key="ViewModel"/>
</Window.Resources>

我认为你应该这样做:

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>

并绑定为:

    <Label Content="{Binding Property}"/>

还要注意你的名称空间:

xmlns:local="clr-namespace:MyNamespace" 

但是您的视图模型似乎在其他地方

试试这个:

在您的ViewModel中,通过名称属性创建一个属性,如:

private string _property;
public string Property
{
    get{ return _property;}
    set{ _property = value;}
}

public MainWindowViewModel()
{
    Property = "test";
}