简体   繁体   English

WPF-将.NET对象属性绑定到窗口属性

[英]WPF - bind an .NET object property to a window property

I have a defined class 我有一个已定义的课程

namespace testApp.ViewsModels
{
 public class myWindowSettings
 {
  public int myWindowHeight { get; set; }
  public String myWindowTitle { get; set; }
  public myWindowSettings()
   {
    myWindowTitle ="My Name Here";
    myWindowHeight =211;
   }
 }
}

And use it as my View Model. 并将其用作我的视图模型。 Within the Window tag of the .xaml I have declared: 在.xaml的Window标记中,我声明了:

xmlns:viewModels="clr-namespace: testApp.ViewsModels"

Within the Windows.Resources I have defined an ObjectDataProvider Windows.Resources我定义了一个ObjectDataProvider

<ObjectDataProvider x:key="myWindowSetting" ObjectType={x:Type viewModels:myWindowSettings}" />

And I can use it to bind to a textBlock Text property 而且我可以用它绑定到textBlock Text属性

<TextBlock x:Name="textBloxk" Text="{Binding Path=myWindowTitle, Source={StaticResource myWindowSetting}, Mode=OneTime}" />

But when I try to bind it to a window property 但是当我尝试将其绑定到窗口属性时

Title="{Binding Path=myWindowTitle, Source={StaticResource myWindowSetting}, Mode=OneTime}"

I got an exception. 我有一个例外。 Exception thrown: 抛出异常:

'System.Windows.Markup.XamlParseException' in PresentationFramework.dll.Additional information: 'Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' 

Line number ... and line position '9'. 行号...和行位置“ 9”。

How can I bind an object of type myWindowSettings to the Window? 如何将myWindowSettings类型的对象绑定到窗口?

Try setting the DataContext of the Window to myWindowSetting , by using the answer to the following question: 通过使用以下问题的答案,尝试将Window的DataContext设置为myWindowSetting

WPF Bind Window Title to ViewModel Property WPF将窗口标题绑定到ViewModel属性

Maybe this will work. 也许这会工作。 I think the problem is that the upper code initializes the window before knowing the Resource myWindowSettings . 我认为问题在于,上面的代码在知道Resource myWindowSettings之前初始化了窗口。 It could also work if you place the ObjectDataProvider object somewhere else. 如果将ObjectDataProvider对象放在其他地方,它也可能起作用。 But for this more of your code would be necessary. 但是为此,您的更多代码将是必需的。

Use following code to bond data-context 使用以下代码绑定数据上下文

<Window.DataContext>
    <viewModels:myWindowSettings x:Name="myWindowSetting" />
</Window.DataContext>

Bind title property as below: 绑定标题属性,如下所示:

Title="{Binding Path = myWindowTitle, Mode=OneTime}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM