绑定的WPF控件的自定义属性的类型 [英] Bind WPF control with property of custom type
问题描述
我想一个标签的内容属性绑定到一些自定义的类型我有一个属性;不幸的是,我也没弄清楚如何做到这一点,这就是为什么我在这里:)
I'm trying to bind a Label's 'Content' property to a property from some custom type I have; unfortunately, I didn't figure out how to do it, and that's why I'm here :)
让我们假设我有以下类型(可以在同一个命名空间作为我的WPF窗口包含标签或不同的命名空间):
Let's assume that I have the following type (can be in the same namespace as my WPF Window that contains the Label or different namespace):
namespace MyNS
{
pubic class Person
{
private int age = 0;
public int Age
{
get { return age; }
}
public void GetOlder
{
age++;
}
}
}
1)如何绑定我的标签我为'年龄'属性?
1) How to I bind my Label to 'Age' property?
2)在运行时,我将创建'人'的实例;我想确保我的标签绑定到正确的实例;也就是说,如果我叫:
2) At runtime I will create an instance of 'Person'; I want to make sure that my Label is bound to the right instance; i.e. if I called:
Person SomePerson = new Person();
SomePerson.GetOlder();
我希望我的标签,可以有'年龄'属性'SomePerson'的新值。
I want my Lable to have the new value of 'Age' property for 'SomePerson'.
3)如果我叫'GetOlder在不同的线程(无论使用调度线程或BackgroundWorker的)?我仍然会得到时代的最新值?还是我必须考虑一些其他的东西护理以及使这种情况可能吗?
3) What if I called 'GetOlder' in different thread (whether using Dispatcher thread or BackgroundWorker)? Will I still get the latest value of 'Age'? Or do I have to take care of some other things as well to make this scenario possible?
由于提前,
TheBlueSky
TheBlueSky
推荐答案
这竟然是一种简单的事情,我不知道为什么没有人回答了:)无论如何,这里有答案:
It turned out to be kind of straightforward thing, I wonder why nobody answered it :) Anyway, here are the answers:
1)首先,我们需要创建Person类是这样的:
1) First we need to create our Person class like this:
using System.ComponentModel;
namespace MyNS
{
pubic class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int age = 0;
public int Age
{
get { return age; }
set
{
age = value;
OnPropertyChanged("Age");
}
}
protected void OnPropertyChanged(string PropertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(PropertyName));
}
}
public void GetOlder
{
Age++;
}
}
}
2)然后我们我们的WPF控件绑定到Person.Age财产是这样的:
2) Then we bind our WPF control to Person.Age property like this:
using System.Windows.Data;
//...
Person p = new Person();
Binding ageBinding = new Binding("Age");
ageBinding.Source = p;
MyWpfLabelControl.SetBinding(Label.ContentProperty, ageBinding);
现在,每当p.GetOlder()被调用MyWpfLabelControl.Content将变更为新的p.Age值。
Now whenever p.GetOlder() is called MyWpfLabelControl.Content will change to the new p.Age value.
3)在多线程的,故事是没有什么不同;调用p.GetOlder()在不同的线程时,它会以同样的方式:
3) In multi-threading, the story is not different; it'll work the same way when calling p.GetOlder() in a different thread:
new Thread(
new ThreadStart(
delegate() {
p.GetOlder();
}
)).Start();
希望这有助于。
TheBlueSky
TheBlueSky
这篇关于绑定的WPF控件的自定义属性的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!