C#中的数据绑定不更新WPF [英] C# data binding doesn't update WPF

查看:597
本文介绍了C#中的数据绑定不更新WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个数据的背后,而不是XAML的C#code绑定。在XAML绑定在Ex pression Blend 2中创建我的CLR对象工作正常。我的C#实现,只有当应用程序启动之后,随后更改了CLR不更新我的标签内容更新。

I'm trying to do a Data Binding in the C# code behind rather than the XAML. The XAML binding created in Expression Blend 2 to my CLR object works fine. My C# implementation only updates when the application is started after which subsequent changes to the CLR doesn't update my label content.

这里的工作XAML绑定。 首先一个ObjectDataProvider的是在我的Window.Resources。

Here's the working XAML binding. First a ObjectDataProvider is made in my Window.Resources.

<ObjectDataProvider x:Key="PhoneServiceDS" 
    ObjectType="{x:Type kudu:PhoneService}" d:IsDataSource="True"/>

和标签内容结合:

<Label x:Name="DisplayName" Content="{Binding 
    Path=MyAccountService.Accounts[0].DisplayName, Mode=OneWay, 
    Source={StaticResource PhoneServiceDS}}"/>

伟大工程。但是,我们希望此建立在C#中,所以我们可以独立改变XAML(即新的皮肤)。我的一次工作的C#如下:

Works great. But we want this set up in C# so we can independently change the XAML (ie. new skins). My one time working C# as follows:

     Binding displayNameBinding = new Binding();
     displayNameBinding.Source = 
         PhoneService.MyAccountService.Accounts[0].DisplayName;
     displayNameBinding.Mode = BindingMode.OneWay;
     this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding);

这是在InitializeComponent()后,我的主窗口内;

This is inside my MainWindow after InitializeComponent();

任何了解为什么在启动时只工作?

Any insight why this only works on startup?

推荐答案

您的C#版本不匹配的XAML版本。它应该可以写你的标记的code版本,虽然我不熟悉的ObjectDataProvider。

Your C# version does not match the XAML version. It should be possible to write a code version of your markup, though I am not familiar with ObjectDataProvider.

尝试是这样的:

Binding displayNameBinding = new Binding( "MyAccountService.Accounts[0].DisplayName" );
displayNameBinding.Source = new ObjectDataProvider { ObjectType = typeof(PhoneService), IsDataSource = true };
displayNameBinding.Mode = BindingMode.OneWay;
this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding);

这篇关于C#中的数据绑定不更新WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆