我有一个简单的表单需要填写,所以我决定添加一些带文本框和标签的DataField。标签可以管理并且长度可以更改,我需要使我的文本框与左侧保持相同的距离。我该如何做到这一点?
tk:DataField.IsFieldGroup="True"
这里的tk是DataField工具包的名称空间,在你想要让所有字段标签宽度相同的父容器上使用。
例如:
<Grid tk:DataField.IsFieldGroup="True">...
这将使标签的宽度与FieldGroup中最长的标签相同。
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Content="Label" Grid.Row="0" Grid.Column="0"/>
<TextBox Grid.Row="0" Grid.Column="1"/>
<Label Content="Long Label" Grid.Row="1" Grid.Column="0"/>
<TextBox Grid.Row="1" Grid.Column="1"/>
我决定使用以下逻辑添加控制:
void MyControl_LayoutUpdated(object sender, EventArgs e)
{
if (this.columnSeparator.ActualWidth!=0&&this.columnSeparator.ActualWidth != this.columnSeparator.MinWidth)
{
this.IsLoaded = true;
SetWidth();
}
}
private void SetWidth()
{
if (IsWidthSet)
return;
if (!this.IsLoaded)
return;
var parentPanel = this.Parent as Panel;
if (parentPanel != null)
{
var textFields = parentPanel.Children.Where(p => p is BpTextField).Cast<BpTextField>().ToList();
double max = this.LabelWidth;
foreach (var textField in textFields)
{
max = Math.Max(max, textField.LabelWidth);
if (!textField.IsLoaded)
return;
}
foreach (var textField in textFields)
{
textField.LabelWidth = max;
}
this.LabelWidth = max;
}
}
public bool IsLoaded { get; set; }
public bool IsWidthSet { get; set; }
现在所有标签都对齐并且排列良好。