【问题标题】:Accessing elements of XAML file in .cs file in WPF在 WPF 中的 .cs 文件中访问 XAML 文件的元素
【发布时间】:2014-02-22 19:06:20
【问题描述】:

我正在创建一个 UI,我有两个 XAML 文件和两个 cs 文件:

Main.xaml Library.xaml

Main.xaml.cs Library.xaml.cs

我已经在Library.xaml 中声明了一个按钮并指定了一个名称my_button,我想在 Main.cs 中访问该按钮。

我该怎么做?

Library.xaml

<Style TargetType="Button">
  <Setter Property="Template">
    <ControlTemplate>
      <Button x:Name=my_button Content="Click"></Button>
    </ControlTemplate>
  </Setter>
</Style>

【问题讨论】:

  • 显示 xaml,我们可以看到这 2 个 xaml 的关系。
  • 也许 TemplateBinding 和 CommandBinding 可以解决您的问题,而不是分配按钮的名称并从 main 访问它。

标签: c# .net wpf xaml controltemplate


【解决方案1】:

如果这两个是独立的(等等。Library 不是 Main 的子级),那么最简单的解决方案是在创建 Library 时通过构造函数或属性注入对象。如果库位于 Main 中,则可以将 x:Name 属性赋予 xaml 中的库,然后像 this.library.my_button 一样访问。

另一种解决方案是使用静态消息服务类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 2011-07-05
    相关资源
    最近更新 更多