WPF在ListBox子元素中设置参数

时间:2019-01-14 13:18:22

标签: c# wpf listbox

我想动态更改ListBox中项目的宽度。
我已经有了这个XAML作为水平列表

<ListBox x:Name="listBox">
     <ListBox.ItemsPanel>
         <ItemsPanelTemplate>
              <UniformGrid IsItemsHost="True" Rows="1" />
         </ItemsPanelTemplate>
     </ListBox.ItemsPanel>
</ListBox>

带有以下.cs(DragAndDrop代码的一部分)

ObservableCollection<int> _List = new ObservableCollection<int>();

public void Fill(int num)
{
    for (int i = 1; i <= num; i++)
    {
       _List.Add(i);
    }
    listBox.ItemsSource = _List;

    Style itemContainerStyle = new Style(typeof(ListBoxItem));
    itemContainerStyle.Setters.Add(new Setter(ListBoxItem.AllowDropProperty, true));
    itemContainerStyle.Setters.Add(new EventSetter(ListBoxItem.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(s_PreviewMouseLeftButtonDown)));
    itemContainerStyle.Setters.Add(new EventSetter(ListBoxItem.DropEvent, new System.Windows.DragEventHandler(listBox_Drop)));

    listBox.ItemContainerStyle = itemContainerStyle;

}

我想动态设置Rows="2",例如基于num的值,并在.cs代码中进行更改,而不是在XAML中将此值设置为静态

1 个答案:

答案 0 :(得分:0)

ItemsPanelTemplate只是一个模板,但是一旦加载ListBox,您就可以使用以下辅助方法在视觉树中找到UniformGrid

private T FindVisualChild<T>(Visual visual) where T : Visual
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
    {
        Visual child = (Visual)VisualTreeHelper.GetChild(visual, i);
        if (child != null)
        {
            T correctlyTyped = child as T;
            if (correctlyTyped != null)
            {
                return correctlyTyped;
            }

            T descendent = FindVisualChild<T>(child);
            if (descendent != null)
            {
                return descendent;
            }
        }
    }
    return null;
}

一旦引用了它,就可以访问它的属性,例如:

System.Windows.Controls.Primitives.UniformGrid grid = FindVisualChild<System.Windows.Controls.Primitives.UniformGrid>(listBox);
if (grid != null)
    grid.Rows = num;