c# – WPF将窗口标题绑定到ViewModel属性

前端之家收集整理的这篇文章主要介绍了c# – WPF将窗口标题绑定到ViewModel属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图将窗口标题绑定到具有Title属性viewmodel.下面是MainWindow XAML:
<Window x:Class="MyProject.View.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:MyProject.viewmodel;assembly=MyProject.viewmodel"
        Title="{Binding Path=Title}" Height="350" Width="525" DataContext="{Binding Source={StaticResource mainWindowviewmodel}}">
    <Window.Resources>
        <vm:MainWindow x:Key="mainWindowviewmodel"/>
    </Window.Resources>

...

</Window>

当我尝试运行它,我得到以下异常“提供值System.Windows.StaticResourceExtension”抛出一个异常.行号和位置指向DataContext属性,内部异常状态“找不到名为mainWindowviewmodel的资源.

以下是View Model的代码

namespace MyProject.viewmodel
{
    public class MainWindow : INotifyPropertyChanged
    {
        #region Fields

        private const string TitlebarPrefixString = "My Project";
        private string title = TitlebarPrefixString;

        public string Title {
            get
            {
                return this.title;
            } // End getter
            set
            {    
                this.title = value;
                OnPropertyChanged("Title");
            } // End setter
        } // End property

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this,new PropertyChangedEventArgs(propertyName));
            } // End if
        } // End method


        public event PropertyChangedEventHandler PropertyChanged;

    } // End class
} // End namespace

我的理论是在试图将标题绑定到属性之后加载资源.抛出异常时,Window的Resources属性为空.

是唯一的解决方案来设置DataContext在代码背后吗?我可以让这个工作,但我宁愿把它保存在XAML.

解决方法

您可以尝试使用属性元素语法设置DataContext:
<Window x:Class="MyProject.View.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:MyProject.viewmodel;assembly=MyProject.viewmodel"
    Title="{Binding Path=Title}" Height="350" Width="525">
<Window.Resources>
    <vm:MainWindow x:Key="mainWindowviewmodel"/>
</Window.Resources>
<Window.DataContext>
  <StaticResourceExtension ResourceKey="mainWindowviewmodel"/>
</Window.DataContext>

这应该在xaml解析器将在资源字典设置完成后执行StaticResourceExtension.

但是我认为甚至可以直接设置DataContext,而不将其声明为资源:

<Window x:Class="MyProject.View.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:MyProject.viewmodel;assembly=MyProject.viewmodel"
    Title="{Binding Path=Title}" Height="350" Width="525">
<Window.DataContext>
    <vm:MainWindow x:Key="mainWindowviewmodel"/>
</Window.DataContext>
原文链接:https://www.f2er.com/csharp/91966.html

猜你在找的C#相关文章