【问题标题】:WPF dynamically create button by style and set control elements insideWPF通过样式动态创建按钮并在里面设置控件元素
【发布时间】:2019-10-26 13:52:43
【问题描述】:

我们的风格定义如下:

<Style x:Key="StartButtonStyle" TargetType="{x:Type Button}">           
 <Setter Property="Template">
   <Setter.Value>
     <ControlTemplate>
       <Button ... Style="{StaticResource StartBtnStyle}">
         <Button.Content>
          <StackPanel>
              <TextBlock x:Name="Line1" Text="..." FontSize="20" />
              <TextBlock x:Name="Line2" Text="..." FontSize="8" />
          </StackPanel>
       </Button.Content>
    </Button>
   </ControlTemplate>
  </Setter.Value>           
 </Setter>      

我们动态创建一个按钮:

var button = new Button() {
    Margin = new Thickness(3d,3d,3d,10d),
    Style = FindResource("StartButtonStyle") as Style,
};

我们要在新按钮内找到“Line1”文本块,并设置Text属性:

var line1 = (TextBlock)button.FindName("Line1");

但它只找到“null”:(我们应该如何在按钮内找到文本块?任何建议都非常感谢!提前致谢!

【问题讨论】:

  • 看看这个线程stackoverflow.com/questions/636383/…你应该检查UI元素树,FindName返回null,因为它位于stackpanel内
  • 你的意思是“FindName”不是递归函数?嗯:(这种特殊情况我可以给stackpanel命名,按名称找到它,然后在里面找到Line1?我应该试试......

标签: wpf templates dynamic properties


【解决方案1】:

等到Style 被应用——在此之前没有TextBlock 元素——到Button,然后在可视化树中找到TextBlock:

var button = new Button()
{
    Margin = new Thickness(3d, 3d, 3d, 10d),
    Style = FindResource("StartButtonStyle") as Style,
};
button.Loaded += (s, e) => 
{
    TextBlock line1 = FindChild<TextBlock>(button, "Line1");
    if(line1 != null)
    {
        line1.Text = "...";
    }
};

递归的FindChild&lt;T&gt;方法来自here。

【讨论】:

  • 我认为(短暂但快乐的时刻)UpdateLayout() 应该足够了——但事实并非如此。 :(但是你的解决方案有效!!谢谢!
猜你喜欢
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 2012-09-05
相关资源
最近更新 更多