![](/img/trans.png)
[英]How to dynamically change grid rows and columns according to window size in WPF
[英]How to dynamically change columns with rows so WPF UserControl appearance is different for each screen
我有一个由两个网格组成的UserControl。
网格中并排有两列,此网格具有水平布局。 第0列有一个数据,第1列有另一个数据。
我需要使用此控件才能将布局从水平更改为垂直,具体取决于应显示此控件的屏幕,因此,而不是让列0和1显示数据,行0和行1现在应该显示数据。
完成此任务的最佳方法是什么?
谢谢
尝试使用StackPanel并将属性Orientation
从Horizontal
更改为Vertical
。
如果您想要比StackPanel提供的更多控制,可以使用ControlTemplates
和DataTriggers
来选择它。 这是一个快速肮脏的例子。
请注意,您可以在不使用UserControl的情况下执行此操作。 我只是在你的描述范围内。
用户控制
<UserControl>
<UserControl.Resources>
<ControlTemplate x:Key="usingColumns">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" ItemsSource="{Binding DataOneItems}" />
<ListBox Grid.Column="1" ItemsSource="{Binding DataTwoItems}" />
</Grid>
</ControlTemplate>
<ControlTemplate x:Key="usingRows">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ListBox Grid.Row="0" ItemsSource="{Binding DataOneItems}" />
<ListBox Grid.Row="1" ItemsSource="{Binding DataTwoItems}" />
</Grid>
</ControlTemplate>
</UserControl.Resources>
<UserControl.Style>
<Style>
<Setter Property="UserControl.Template" Value="{StaticResource usingColumns}" />
<Style.Triggers>
<DataTrigger Binding="{Binding ShowVertically}" Value="true">
<Setter Property="UserControl.Template" Value="{StaticResource usingRows}" />
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Style>
</UserControl>
绑定到用户控件的类:
public class UserControlData
{
public ReadOnlyObservableCollection<DataTypeOne> DataOneItems
{
get
{
ObservableCollection<DataTypeOne> dataOneItems = new ObservableCollection<DataTypeOne>();
for (int i = 1; i <= 3; i++)
dataOneItems.Add(new DataTypeOne(i));
return new ReadOnlyObservableCollection<DataTypeOne>(dataOneItems);
}
}
public ReadOnlyObservableCollection<DataTypeTwo> DataTwoItems
{
get
{
ObservableCollection<DataTypeTwo> dataTwoItems = new ObservableCollection<DataTypeTwo>();
for (int i = 1; i <= 3; i++)
dataTwoItems.Add(new DataTypeTwo(i));
return new ReadOnlyObservableCollection<DataTypeTwo>(dataTwoItems);
}
}
public bool ShowVertically
{
get;
set;
}
}
虚拟数据类型(除类名外,DataTypeOne和DataTypeTwo相同):
public class DataTypeOne
{
private readonly int mId = 0;
public DataTypeOne(int id)
{
mId = id;
}
public int ID
{
get { return mId; }
}
public override string ToString()
{
return String.Format("I am a DataTypeOne with ID {0}", mId.ToString("N"));
}
}
关键是ControlTemplates(一个用于水平,一个用于垂直)和StyleTrigger在Style上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.