2

Есть ссылка на кнопку var button

var button = new Button();
button.ContentTemplate...

Как реализовать программно XAML код?

XAML:

<Button >
    <Button.ContentTemplate>
        <DataTemplate>
            <WrapPanel >
                <TextBlock />
            </WrapPanel>
        </DataTemplate>
    </Button.ContentTemplate>
</Button>
2
  • 1
    Эх, MVVM вам не хватает...
    – MihailPw
    29 мая 2017 в 12:01
  • Зачем вручную контакт создавать?
    – Alex78191
    29 мая 2017 в 12:19

1 ответ 1

4
DataTemplate template = new DataTemplate();

FrameworkElementFactory wrapPanel = new FrameworkElementFactory(typeof(WrapPanel));            
FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock));    

textBlock.SetValue(TextBlock.TextProperty, "some text");//добавим текст 
wrapPanel.AppendChild(textBlock);  

template.VisualTree = wrapPanel;

button.ContentTemplate = template;

Второй вариант с использованием XamlRedaer:

string temp = @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> 
                    <WrapPanel>
                        <TextBlock/>
                    </WrapPanel>                            
                </DataTemplate>";

StringReader stringReader = new StringReader(temp);
XmlReader xmlReader = XmlReader.Create(stringReader)

DataTemplate template =  XamlReader.Load(xmlReader) as DataTemplate;
button.ContentTemplate = template;
4
  • почему в первом варианте ошибка при textBlock.Text = "1"; &? System.ArgumentException: "Не удается добавить текст "1", так как текст не является допустимым в данном элементе." ` $exception Не удается вычислить выражение. `
    – code211218
    29 мая 2017 в 13:32
  • @codename0082016, потому что textBlock в данном случае не является экземпляром TextBlock на самом деле. Обновил ответ, смотрите.
    – Gardes
    29 мая 2017 в 13:40
  • Ого, классно! Не знал, как создавать шаблоны в коде.
    – VladD
    29 мая 2017 в 14:54
  • 1
    @VladD, я тоже, до сегодняшнего дня)
    – Gardes
    29 мая 2017 в 15:45

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.