我希望创建一个与对象列表绑定的水平布局,其中包含一些要显示的信息。我希望此控件中的控件大小可以自动伸缩填充整个控件,就像UniformGrid一样。
问题在于,我不想控件的宽度是均匀分配的,而是基于对象本身的属性进行加权分配。
我认为使用自定义的ItemsPanelTemplate的ItemsControl将是一个不错的策略,因为它与UniformGrid很好地配合使用:
<ItemsControl x:Name="itemsControl" ItemsSource="{Binding MyResults}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="1">
<TextBlock Width="{Binding Weight}" Text="{Binding Weight}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
绑定到视图模型:
public class MainViewModel : PropertyChangedBase
{
public List<MyTestClass> MyResults { get; set; } = new List<MyTestClass>()
{
new MyTestClass() { Weight = 25 },
new MyTestClass() { Weight = 50 },
new MyTestClass() { Weight = 25 }
};
}
public class MyTestClass
{
public int Weight { get; set; }
}
一个想法是切换到普通的网格(Grid),并使用列定义 *-宽度行为(例如 (25*,50*,25*)
但绑定为 Weight*
),但我无法弄清楚如何做到这一点。