更改ListBox UniformGrid列数的最佳方法是什么?

时间:2013-06-26 20:28:59

标签: c# wpf listbox wpf-controls

我有ListBox UniformGrid布局,我正在尝试更改“列”属性,但我不知道这样做的最佳方式。我尝试绑定到属性或以编程方式创建新布局,但我无法弄明白。

<ListBox x:Name="ImagesList" ItemsSource="{Binding Path=GridImages}">
        <ListBox.ItemsPanel>

            <ItemsPanelTemplate>
                <UniformGrid IsItemsHost="True" Columns="3" VerticalAlignment="Top" />
            </ItemsPanelTemplate>

        </ListBox.ItemsPanel>
</ListBox>

当用户点击两个按钮时,我正在尝试更改1到3列。我尝试使用Columns="{Binding Path=MyColumnCount}"绑定,但它永远不会更改,并尝试设置x:Name并从我的代码访问,但没有成功。我还试图实例化一个新的UniformGrid,但我读过我需要一个工厂,所以我不能设置不同的Columns值。

1 个答案:

答案 0 :(得分:1)

我想也许ItemsPanelTemplate没有继承ListBox'DataContext,但确实如此,所以Binding应该有效:

<ListBox x:Name="ImagesList" ItemsSource="{Binding Path=GridImages}" >
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid IsItemsHost="True" Columns="{Binding Path=MyColumnCount}"
                         VerticalAlignment="Top" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

    <ListBox.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

尝试使用这个简单的ViewModel来更新计时器上的MyColumnCount

public class ImagesVM : INotifyPropertyChanged
{
    private System.Threading.Timer _timer;
    private int _colIncrementor = 0;

    public ImagesVM()
    {
        _timer = new System.Threading.Timer(OnTimerTick, null,
                                            TimeSpan.FromSeconds(1),
                                            TimeSpan.FromSeconds(1));
        _gridImages = new string[] {
            "http://www.anbg.gov.au/images/flags/semaphore/a-icon.gif",
            "http://www.anbg.gov.au/images/flags/semaphore/b-icon.gif",
            "http://www.anbg.gov.au/images/flags/semaphore/c-icon.gif",
            "http://www.anbg.gov.au/images/flags/semaphore/d-icon.gif",
            "http://www.anbg.gov.au/images/flags/semaphore/e-icon.gif",
            "http://www.anbg.gov.au/images/flags/semaphore/f-icon.gif",
        };
    }
    private void OnTimerTick(object state)
    {
        this.MyColumnCount = (_colIncrementor++ % 3) + 1;
    }

    private int _myColumnCount = 3;
    public int MyColumnCount
    {
        get { return _myColumnCount; }
        set
        {
            _myColumnCount = value;
            this.PropertyChanged(this, new PropertyChangedEventArgs("MyColumnCount"));
        }
    }

    private string[] _gridImages = null;
    public string[] GridImages
    {
        get { return _gridImages; }
    }

    public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };
}