WPF麻烦在UserControl中使用依赖属性 [英] wpf trouble using dependency properties in a UserControl
问题描述
我制作了一个UserControl,旨在每隔几秒钟使用来自串行端口的数据进行一次更新。该UserControl应该非常简单,由一个用于字段名称的Label和另一个包含该字段值的Label组成。我说它应该很简单,但是没有用。它根本不会更新,甚至不显示字段名称。
I made a UserControl that is meant to be updated once every few seconds with data from a serial port. This UserControl should be very simple, consisting of a Label for a field name, and another Label containing the field value. I say that it should be simple, but it doesn't work. It does not update at all, and doesn't even display the field name.
下面是代码:
public partial class LabeledField : UserControl {
public LabeledField() {
InitializeComponent();
}
public string fieldName {
get { return fieldNameLabel.Content.ToString(); }
set { fieldNameLabel.Content = value; }
}
public string fieldValue {
get { return (string)GetValue(fieldValueProperty); }
set { SetValue(fieldValueProperty, value); }
}
public static readonly DependencyProperty fieldValueProperty =
DependencyProperty.Register(
"fieldValue",
typeof(string),
typeof(LabeledField),
new FrameworkPropertyMetadata(
"No Data"
)
)
;
}
这是XAML:
<UserControl x:Class="DAS1.LabeledField" Name="LF"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Orientation="Horizontal">
<Label Width="100" Height="30" Background="Gray" Name="fieldNameLabel" />
<Label Width="100" Height="30" Background="Silver" Name="fieldValueLabel" Content="{Binding fieldValue}" />
</StackPanel>
这是XAML用于引用UserControl的窗口。首先是标题:
And here is the XAML for the Window which references the UserControl. First the header:
<Window x:Class="DAS1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:me="clr-namespace:DAS1"
Title="Window1" Height="580" Width="780">
然后,UserControl本身:
Then the UserControl itself:
<me:LabeledField fieldName="Test" Width="200" Height="30" fieldValue="{Binding businessObjectField}"/>
如果我知道要问的更具体的问题,我会-但有人可以告诉我为什么
If I knew of a more specific question to ask, I would--but can anyone tell me why this doesn't work?
推荐答案
原来,在XAML用户控件中,绑定指定不正确。
Turns out that in the XAML for the user control, the binding was incorrectly specified.
最初是:
<Label Width="100" Height="30" Name="fieldValueLabel" Content="{Binding fieldValue}" />
但是我没有指定fieldValue所属的元素。应该是(假设我的用户控件名为 LF:
But I had not specified the element to which fieldValue belongs. It should be (assuming my user control is named "LF":
<Label Width="100" Height="30" Name="fieldValueLabel" Content="{Binding ElementName=LF, Path=fieldValue}" />
这篇关于WPF麻烦在UserControl中使用依赖属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!