从后面的代码创建DataTemplate

时间:2012-11-14 10:02:17

标签: c# wpf

对不那么普遍的问题抱歉...

我有一个ListView,我必须从后面的代码填充,这个ListView也需要从后面的代码中获取它的GridViewColumn。

对于字符串来说,连接起来并不困难,但现在我不想在ListView中创建一个表示布尔值的椭圆。

XAML中的代码相当简单,但我无法将其转换为c#代码。

以下是XMAL代码的一部分:

<ResourceDictionary>
    <BooleanToVisibilityConverter x:Key="BoolToVisibility" />
    <DataTemplate x:Key="templateAdmin">
        <DockPanel>
            <Ellipse Width="8" Height="8" Visibility="{Binding Path=isAdmin, Converter={StaticResource BoolToVisibility}}" Fill="Black"/>
        </DockPanel>
    </DataTemplate>
</ResourceDictionary>

<ListView>
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding LastName}" Header="Last Name"/>
            <GridViewColumn CellTemplate="{StaticResource templateAdmin}"
                <GridViewColumnHeader">
                    <TextBlock Text="S"/>
                </GridViewColumnHeader>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

到目前为止,我已经走到了这一步: XAML:

<local:SortableListView >
    <ListView.View>
        <GridView x:Name="GroupListGridView" />
    </ListView.View>
</local:SortableListView>

在代码中,我有一个Collection<GridViewColumn> GridViewColumns,我循环播放并将所有项目添加到GroupListGridView。我有一个函数来填充GridViewColumns集合:

private void CreateGridViews()
{
    //Creating the Text was easy!
    GridViewColumns.add(new GridViewColumn(){ Header = "LastName", DisplayMemberBinding = new Binding("LastName") });

    //Creating the Ellipse was harder!
    GridViewColumn gvc = new GridViewColumn();
    DataTemplate dt = new DataTemplate();

    gvc.DisplayMemberBinding = new Binding("isAdmin");
    FrameworkElementFactory fef = new FrameworkElementFactory(typeof(Ellipse));
    fef.SetValue(Ellipse.WidthProperty, 8.0D);
    fef.SetValue(Ellipse.HeightProperty, 8.0D);
    fef.SetValue(Ellipse.FillProperty, new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Black));

    //I'm guessing that somewhere here there should be some binding to the visibility property and some sort of conversion done... But I can't figure out how!

    dt.VisualTree = fef;
    gvc.CellTemplate = dt;
    GridViewColumns.Add(gvc);
}

我不认为我是那么远......只是我无法弄清楚那些最后的步骤!

1 个答案:

答案 0 :(得分:0)

缺少的行是:

var ellipseVisBinding = new Binding("isAdmin");
ellipseVisBinding.Converter = new BooleanToVisibilityConverter();

fef.SetBinding(Ellipse.VisibilityProperty, ellipseVisBinding);

(我注意到你已经从代码版本中排除了模板中的DockPanel,所以我也删除了它)