WPF ListBox 控件绑定 Binding

当我们需要用到循环的列表内容,并且模板化程度高的时候,建议使用 ListBox 来做绑定。

XAML:

<Window.DataContext>
    <local:VMTempTest/>
</Window.DataContext>
<StackPanel Margin="10,0,0,50" Orientation="Vertical" >
    <TextBlock Text="ListBox 模板" FontWeight="Bold"  Margin="0,5,0,5" ></TextBlock>
    <DockPanel >
        <StackPanel HorizontalAlignment="Left" DockPanel.Dock="Top" >
            <ListBox x:Name="lb" ItemsSource="{Binding ListBoxData}" BorderThickness="0" >
                <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel Width="{Binding ActualWidth,RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"/>
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>

                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <Image Source="{Binding Img}" Width="96" Height="96"/>
                            <TextBlock HorizontalAlignment="Center" FontSize="16" Text="{Binding Info}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </StackPanel>

        <StackPanel DockPanel.Dock="Bottom" DataContext="{Binding SelectedItem,ElementName=lb}" Margin="15 30 0 0" HorizontalAlignment="Left" Orientation="Vertical" >
            <TextBlock Text="{Binding Info,StringFormat='选中:\{0\}'}" ></TextBlock>
        </StackPanel>
    </DockPanel>
</StackPanel>

ViewModel:

public class VMTempTest : ViewModelBase
{
    public VMTempTest()
    {
        ListBoxData = new ObservableCollection<dynamic>(){
          new { Img="/MyWpfApp;component/Images/1.jpg",Info="樱桃" },
          new { Img="/MyWpfApp;component/Images/2.jpg",Info="葡萄" },
          new { Img="/MyWpfApp;component/Images/3.jpg",Info="苹果" },
          new { Img="/MyWpfApp;component/Images/4.jpg",Info="猕猴桃" },
          new { Img="/MyWpfApp;component/Images/5.jpg",Info="柠檬" },
       };
    }

    private IEnumerable listBoxData;
    /// <summary>
    /// LisBox数据模板
    /// </summary>
    public IEnumerable ListBoxData
    {
        get { return listBoxData; }
        set { listBoxData = value; RaisePropertyChanged(() => ListBoxData); }
    }
}

注意:要将放图片的 Images 文件件包含到项目中来。Img="/MyWpfApp;component/Images/1.jpg" 这个初始化路径也可以简化成 Img="/Images/1.jpg"




posted @ 2021-08-14 07:59  double64  阅读(749)  评论(0编辑  收藏  举报