【问题标题】:WPF C#: Access the children of a button in the code behindWPF C#:在后面的代码中访问按钮的子项
【发布时间】:2021-01-13 16:19:07
【问题描述】:
<Button Name="B1">
    <Grid>
        <Label/>
        <Label/>
    </Grid>
</Button>
<Button Name="B2">
    <Grid>
        <Label/>
        <Label/>
    </Grid>
</Button>
<Button Name="B3">
    <Grid>
        <Label/>
        <Label/>
    </Grid>
</Button>

如何在不使用名称属性的情况下访问 B2 标签 2。类似的东西:

B2.Children[0].Children[1].Content = "Thank You <3"

【问题讨论】:

  • ((Label)((Grid)B2.Content).Children[1]).Content = "Like this"; 但是,为特定视图模型类型创建一个 DataTemplate 会更有意义,该类型包含具有两个标签的网格,其中标签的内容绑定到视图模型类的属性。然后将该类的一个实例分配给 Button 的 Content 属性。
  • 您为我节省了很多时间,非常感谢!对于对象转换,我使用扩展名,因此您的代码如下: B2.Content.Root().Children[0].Root
  • 这对我来说没有任何意义。它是一种执行显式强制转换的静态方法 - 作为直接编写该强制转换的替代品。完全没有意义,对不起。考虑使用 DataTemplate 方法。这是有道理的。
  • 为什么要避免使用 name 或 x:Name 属性?
  • @UuDdLrLrSs 假设我想在单击按钮时更改第一个标签的背景,我可以执行以下操作:Container.Children.OfType&lt;Button&gt;().ToList().ForEach(x =&gt; x.Click += (s, e) =&gt; x.Content.Root&lt;Grid&gt;().Children[0].Root&lt;Label&gt;().Background = new SolidColorBrush(Color.FromRgb(0, 0, 0))); 但使用名称属性对我来说将是一个问题所以。

标签: wpf visual-studio wpf-controls


【解决方案1】:

您可以使用触发器根据点击按钮更改标签背景,如下所示:

  <Style TargetType="Label" x:Key="MyLable">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsPressed,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Button}}}"  Value="true">
                <Setter Property="Background" Value="Blue" ></Setter>
            </DataTrigger>
        </Style.Triggers>
    </Style>

【讨论】:

  • 感谢您的回复,根据文档:一旦条件不再满足,触发器将重置为初始状态。我想要实现的是在单击按钮后永久更改背景颜色。这就是我在后面的代码中创建它的原因。
  • @ynsbl.eng,可以按类型获取子元素,更多信息请参考:stackoverflow.com/questions/10279092/…
猜你喜欢
  • 1970-01-01
  • 2017-02-09
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-04
  • 1970-01-01
相关资源
最近更新 更多