假设我有一个非常简单的UserControl - 对于所有意图和目的 - 只不过是TextBox:
public partial class FooBox : UserControl
{
public static readonly DependencyProperty FooTextProperty =
DependencyProperty.Register("FooText", typeof(string), typeof(FooBox));
public FooBox()
{
InitializeComponent();
}
public string FooText
{
get { return textBlock.Text; }
set { textBlock.Text = value; }
}
}
<UserControl x:Class="Namespace.FooBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid>
<TextBlock x:Name="textBlock" />
</Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
在表格上,它被声明为:
<local:FooBox FooText="{Binding Name}" />
Run Code Online (Sandbox Code Playgroud)
表单的DataContext设置为具有Name属性的对象.但这不适合我.我错过了什么?
我创建了一个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 …Run Code Online (Sandbox Code Playgroud)