【发布时间】:2015-09-10 22:12:37
【问题描述】:
我正在尝试使用 C# 和 XAML 在 Windows 通用应用程序中实现标记为 TextBox,但我没有得到 TextBox 的值作为回报,只是空字符串。
我的 generic.xaml 的代码如下所示:
<Style TargetType="template:LabeledTextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="template:LabeledTextBox">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="{TemplateBinding Label}" FontWeight="Bold" VerticalAlignment="Center" Margin="10,0" />
<TextBox Text="{TemplateBinding Value}" IsReadOnly="{TemplateBinding IsReadOnly}" VerticalAlignment="Center" Margin="20,0,10,0" Grid.Row="1" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
控件如下所示:
public sealed class LabeledTextBox : Control, IParameterReturnable
{
public static readonly DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(string), typeof(LabeledTextBox), new PropertyMetadata(default(string)));
public string Label
{
get { return this.GetValue(LabelProperty).ToString(); }
set { this.SetValue(LabelProperty, value); }
}
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(LabeledTextBox), new PropertyMetadata(default(string)));
public string Value
{
get { return this.GetValue(ValueProperty).ToString(); }
set { this.SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(LabeledTextBox), new PropertyMetadata(false));
public string IsReadOnly
{
get { return this.GetValue(IsReadOnlyProperty).ToString(); }
set { this.SetValue(IsReadOnlyProperty, value); }
}
public LabeledTextBox()
{
this.DefaultStyleKey = typeof(LabeledTextBox);
}
public LabeledTextBox(Parameter parameter)
{
this.Label = parameter.DisplayName;
this.Value = parameter.DefaultValue ?? "";
this.DefaultStyleKey = typeof(LabeledTextBox);
}
public string GetKey()
{
return this.Label;
}
public string GetValue()
{
return this.Value;
}
}
您可以随意忽略我的 IParameterReturnable,我使用它来访问 GetKey() 和 GetValue(),同时循环通过不同类型的这些标记控件。
那么我错过了什么,我做错了什么?
非常感谢您提供的所有有用且善意的答案!
编辑:添加控件的代码
使用 C# 动态添加控件,如下所示:
foreach (Parameter parameter in parameters)
{
stackPanel.Children.Add(new LabeledTextBox(parameter));
}
但它在 Xaml 中看起来像这样:
<templates:LabeledTextBox Label="[Label]" Value="[Value]" IsReadOnly="False" />
会这样读出:
foreach(IParameterReturnable parameter in stackPanel.Children)
{
string val = parameter.GetValue() // <= this will always return the default value
}
【问题讨论】:
-
你能分享你放置 LabeledTextBox 的 xaml
-
对于我循环遍历这些的特殊情况,控件是由 c# 而不是 xaml 动态添加到堆栈面板的
-
那么您如何设置标签和文本属性?那你能把代码添加到问题中吗?
-
条目已用代码更新
-
如果你不使用
Tag属性,你可以用它来显示标签,而不需要扩展TextBox控件。
标签: c# wpf xaml custom-controls win-universal-app