我的小目标是实现动态的动态生成控件并关联它们各自的属性,例如 Visibility 和 IsEnabled。
控件必须插入 StackPanel。并且基于某些条件,子节点的属性会发生变化。我使用了以下嵌套的 StackPanel 结构:
- 具有子项垂直方向的父 StackPanel(标签和输入字段的集合以模拟表单)
- 水平方向的子节点 StackPanel(标签和输入字段)
主要思想是每个标签只有一个输入字段:日期选择器、组合、文本或任何其他字段。结果,我创建了一个标签和一个带有多个控件的网格。我通过转换器操作输入控件的 Visibility 和 IsEnabled 属性。
问题是:是否有可能通过其他方式(更有效/更美观)来实现所有这些?非常欢迎建设性的批评和建议:)
先感谢您。
XAML:
<StackPanel Grid.Row="1" Orientation="Vertical">
<ItemsControl ItemsSource="{Binding DataClass}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0, 5, 0, 0" >
<Label Content="{Binding KeyName}" Width="150"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="190"/>
</Grid.ColumnDefinitions>
<DatePicker Text="{Binding Value}"
Visibility="{Binding Type, Converter={StaticResource TypeVisiblity}, ConverterParameter='DateTime'}"
IsEnabled="{Binding RelativeSource={x:Static RelativeSource.Self}, Converter={StaticResource VisibilityEnabled}}"/>
<ComboBox Text="{Binding Value}"
Visibility="{Binding Type, Converter={StaticResource TypeVisiblity}, ConverterParameter='Lookup'}"
IsEnabled="{Binding RelativeSource={x:Static RelativeSource.Self}, Converter={StaticResource VisibilityEnabled}}"/>
<TextBox Text="{Binding Value}"
Visibility="{Binding Type, Converter={StaticResource TypeVisiblity}, ConverterParameter='Number'}"
IsEnabled="{Binding RelativeSource={x:Static RelativeSource.Self}, Converter={StaticResource VisibilityEnabled}}"/>
<TextBox Text="{Binding Value}"
Visibility="{Binding Type, Converter={StaticResource TypeVisiblity}, ConverterParameter='Text'}"
IsEnabled="{Binding RelativeSource={x:Static RelativeSource.Self}, Converter={StaticResource VisibilityEnabled}}"/>
</Grid>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
可见性转换器:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool isMatched;
string type,
controlType;
// Safe Convert.
type = System.Convert.ToString(value);
controlType = System.Convert.ToString(parameter);
if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(controlType))
{
return Visibility.Hidden;
}
// Check matching.
isMatched = string.Equals(type, controlType, StringComparison.CurrentCultureIgnoreCase);
return isMatched ? Visibility.Visible : Visibility.Hidden;
}
IsEnabled 转换器:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Control control;
control = value as Control;
if (control == null)
{
return false;
}
return control.Visibility == Visibility.Visible;
}