XAML到C#代码:将图像绑定到ListView

时间:2018-02-07 13:50:45

标签: c# wpf xaml listview

我正在尝试通过代码绑定ListView中的图像。目标是在C#中编写这段代码。如何在代码中绑定工作? 这是我的xaml代码:

<ListView x:FieldModifier="public" x:Name="MyListView" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding ListViewDataList}">
    <ListView.View>
        <GridView x:Uid="GridViewTest">
            <GridViewColumn Header="Column1" DisplayMemberBinding="{Binding Column1Text}"/>
            <GridViewColumn Header="Column2">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Width="50" Height="50" Source="{Binding Column2Img}"/>
                        </StackPanel>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

Column1Text Column2Img 是属性。 我试过这样的事情:

GridView MyGridView = new GridView();

GridViewColumn gvc1 = new GridViewColumn();
gvc1.DisplayMemberBinding = new Binding("Column1Text");
gvc1.Header = "Column1";
MyGridView.Columns.Add(gvc1);

System.Windows.Controls.Image img = new System.Windows.Controls.Image();
img.Height = 50;
img.Width = 50;
img.Source = new Binding("Column2Img");

FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(StackPanel));
spFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
DataTemplate dt = new DataTemplate();
dt.VisualTree = spFactory;

GridViewColumn gvc2 = new GridViewColumn();
gvc2.Header = "Column2";
gvc2.CellTemplate = dt;
MyGridView.Columns.Add(gvc2);

MyListView.View = MyGridView;

但是后面代码中的图像绑定不起作用。

1 个答案:

答案 0 :(得分:1)

您应绑定Source属性,而不是直接将其设置为Binding对象:

img.SetBinding(Image.SourceProperty, new Binding("Column2Img"));

但您还需要为添加到FrameworkElementFactory的{​​{1}}元素创建Image

spFactory

请注意,使用FrameworkElementFactory imgFactory = new FrameworkElementFactory(typeof(Image)); imgFactory.SetValue(Image.HeightProperty, 50.0); imgFactory.SetValue(Image.WidthProperty, 50.0); imgFactory.SetBinding(Image.SourceProperty, new Binding("Column2Img")); FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(StackPanel)); spFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal); spFactory.AppendChild(imgFactory); 是以编程方式创建模板的弃用方式:https://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory(v=vs.110).aspx

  

以编程方式创建模板的推荐方法是使用FrameworkElementFactory类的string方法从Load或内存流加载XAML。