Kla*_*lay 8 wpf user-controls dependency-properties
我创建了一个UserControl,每隔几秒就会使用串行端口的数据进行一次更新.此UserControl应该非常简单,包含字段名称的Label和包含字段值的另一个Label.我说它应该很简单,但它不起作用.它根本不更新,甚至不显示字段名称.
以下是代码:
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"
)
)
;
}
Run Code Online (Sandbox Code Playgroud)
这是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>
Run Code Online (Sandbox Code Playgroud)
这里是引用UserControl的Window的XAML.首先是标题:
<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">
Run Code Online (Sandbox Code Playgroud)
然后是UserControl本身:
<me:LabeledField fieldName="Test" Width="200" Height="30" fieldValue="{Binding businessObjectField}"/>
Run Code Online (Sandbox Code Playgroud)
如果我知道要问一个更具体的问题,我会 - 但是有谁可以告诉我为什么这不起作用?
事实证明,在用户控件的XAML中,未正确指定绑定.
最初它是:
<Label Width="100" Height="30" Name="fieldValueLabel" Content="{Binding fieldValue}" />
Run Code Online (Sandbox Code Playgroud)
但我没有指定fieldValue所属的元素.它应该是(假设我的用户控件名为"LF":
<Label Width="100" Height="30" Name="fieldValueLabel" Content="{Binding ElementName=LF, Path=fieldValue}" />
Run Code Online (Sandbox Code Playgroud)
如果要绑定到控件的属性,则应在绑定中指定.绑定是相对于DataContext它们的源是否未明确指定而进行评估的,因此绑定不会绑定到您的控件,而是绑定到继承的上下文(可能缺少您绑定的属性).你需要的是:
<Label Width="100" Height="30" Name="fieldValueLabel"
Content="{Binding Path=fieldValue, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DAS1.LabeledField}}}" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17104 次 |
| 最近记录: |