使用Frameworkelementfactory不更新按钮内容

时间:2012-02-15 15:13:24

标签: c# wpf dynamic

我一直在尝试使用可爱的Frameworkelementfactory创建一个ContentTemplate。

代码有效,但我无法设置Button的内容。我尝试了很多东西,但总是最终得到一个带Content = Button的按钮。

以下是生成contenttemplate的代码。有关详细信息,我在Tabcontrol Header Itemtemplate中使用它...

干杯。

ControlTemplate ct = new ControlTemplate(typeof(TabItem));

FrameworkElementFactory spouter = new FrameworkElementFactory(typeof    (DockPanel));
FrameworkElementFactory text = new FrameworkElementFactory(typeof(TextBlock));
text.SetValue(TextBlock.TextProperty, Name);
spouter.AppendChild(text);

FrameworkElementFactory mButtonPrev = new FrameworkElementFactory(typeof(Button));
mButtonPrev.SetValue(System.Windows.Controls.Button.ContentProperty, "x");
mButtonPrev.AddHandler(System.Windows.Controls.Button.ClickEvent, new RoutedEventHandler(CloseTab));
spouter.AppendChild(mButtonPrev);
ct.VisualTree = spouter;
return ct;

2 个答案:

答案 0 :(得分:0)

ControlTemplate ct = new ControlTemplate(typeof(TabItem));

你不应该在这里创建一个DataTemplate吗?

(其他一切看起来都很好,FEF也已弃用,请the docs

答案 1 :(得分:0)

对于仍在使用FEF的用户,我能够使用实际字符串设置我的按钮的内容。我将Name视为示例中“按钮”的来源。在我的示例中,Name提取了我绑定到datagrid的类名。

    var buttonTemplate = new FrameworkElementFactory(typeof(Button));
    var text = new FrameworkElementFactory(typeof(TextBlock));
    text.SetValue(TextBlock.TextProperty, "Save");
    buttonTemplate.AppendChild(text);
    buttonTemplate.AddHandler(
        System.Windows.Controls.Primitives.ButtonBase.ClickEvent,
        new RoutedEventHandler((o, e) => MessageBox.Show("hi"))
    );

    AccountDatagrid.Columns.Add(new DataGridTemplateColumn()
    {
        Header = "Save",
        CellTemplate = new DataTemplate() { VisualTree = buttonTemplate }
    });
    AccountDatagrid.ItemsSource = AccoutDescCodeTime.GetBaseAccounts();