[英]Insert Labels with ItemsControl in Grid
我想將標簽從 ItemsControl 排序到我的網格。 當我綁定 Grid.Row 和 Grid.Column 屬性時,列和行的 position 不受影響。 我究竟做錯了什么?
這是我的觀點。xaml
<Window.Resources>
<vm:MainViewModel x:Key="MainVM"/>
</Window.Resources>
<DockPanel DataContext="{StaticResource MainVM}">
<Grid Width="500">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ItemsControl
ItemsSource="{Binding MachineList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" Background="Gainsboro" BorderThickness="1" Margin="2">
<Label Content="{Binding SerialNumber}"
Grid.Column="{Binding StationNumber}"
Grid.Row="{Binding LineNumber}"
Margin="0"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Background="LightBlue"
/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</DockPanel>
這是我的 MainViewModel.cs
public class MainViewModel: BaseViewModel
{
public ObservableCollection<Machine> MachineList { get; set; }
public MainViewModel()
{
Machine m1 = new Machine(0, "Row1 Column3", 1, 3, MachineType.SX);
Machine m2 = new Machine(0, "Row1 Column2", 1, 2, MachineType.SX);
Machine m3 = new Machine(0, "Row2 Column1", 2, 1, MachineType.SX);
MachineList = new ObservableCollection<Machine>();
MachineList.Add(m1);
MachineList.Add(m2);
MachineList.Add(m3);
}
}
問題是ItemsControl
在自己的面板中顯示項目,這不是您的網格,因此 grid 屬性對項目的位置沒有影響。 正確的方法是在ItemsControl.ItemsPanel
屬性中定義網格,如下所示:
<ItemsControl
ItemsSource="{Binding MachineList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" Background="Gainsboro" BorderThickness="1" Margin="2">
<Label Content="{Binding SerialNumber}"
Margin="0"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Background="LightBlue"
/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid Width="500">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Row" Value="{binding ...}" />
<Setter Property="Grig.Column" Value="{binding ...}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
請參閱此處的 ItemsPanelTemplate 屬性部分
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.