gpt4 book ai didi

c# - ItemsControl中子元素的加权分布

转载 作者:行者123 更新时间:2023-11-30 17:38:23 25 4
gpt4 key购买 nike

我想创建一个绑定(bind)到对象列表的水平布局,其中包含一些要显示的信息。我希望此控件中控件的大小能够像 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>

绑定(bind)到 View 模型:

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; }
}

一个想法是切换到普通网格并使用 ColumnDefinitions *-width 行为(如 (25*,50*,25*) 但绑定(bind)为 Weight*),但我不知道该怎么做。

最佳答案

使用自定义 Panel 实现会容易得多。我会选择这样的东西:

public class WeightedPanel : Panel
{
public static double GetWeight(DependencyObject obj)
{
return (double)obj.GetValue(WeightProperty);
}

public static void SetWeight(DependencyObject obj, double value)
{
obj.SetValue(WeightProperty, value);
}

public static readonly DependencyProperty WeightProperty =
DependencyProperty.RegisterAttached("Weight", typeof(double), typeof(WeightedPanel), new PropertyMetadata(1.0));

private double totalWeight_;
protected override Size MeasureOverride(Size availableSize)
{
totalWeight_ = 0;
foreach (UIElement child in InternalChildren)
{
totalWeight_ += WeightedPanel.GetWeight(child);
child.Measure(availableSize);
}

return new Size(0, 0);
}

protected override Size ArrangeOverride(Size finalSize)
{
double offset = 0;
foreach (UIElement child in InternalChildren)
{
var weight = WeightedPanel.GetWeight(child);
var width = finalSize.Width * weight / totalWeight_;

child.Arrange(new Rect(new Point(offset, 0), new Size(width, finalSize.Height)));

offset += width;
}

return finalSize;
}
}

用法

    <local:WeightedPanel>
<Border local:WeightedPanel.Weight="25" Background="Green"></Border>
<Border local:WeightedPanel.Weight="50" Background="Red"></Border>
<Border local:WeightedPanel.Weight="25" Background="Blue"></Border>
</local:WeightedPanel>

关于c# - ItemsControl中子元素的加权分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36743655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com