【问题标题】:How do I Access Buttons inside a UserControl from xaml?如何从 xaml 访问 UserControl 内的按钮?
【发布时间】:2017-02-14 15:53:33
【问题描述】:

在工作中,我有几个页面,每个页面的按钮都在相同的位置,并且具有相同的属性。每一页也有细微的差别。为此,我们创建了一个用户控件模板并将所有按钮放入其中,然后将该用户控件应用于所有页面。然而,现在访问按钮并从每个页面的 xaml 修改它们相当困难,因为它们位于页面上的 UserControl 内..... 我如何优雅地访问每个页面的按钮?

我的尝试:

  1. 目前,我们绑定到一堆依赖属性。我不喜欢这个选项,因为我有很多按钮,并且需要控制这些按钮的很多属性。结果是数百个依赖属性,当我们需要更改某些内容时,真的是一团糟。

  2. 另一种方法是使用样式。我一般喜欢这种方法,但由于这些按钮位于另一个控件中,因此很难修改它们,而且模板一次只能完全正确地处理一个按钮。

  3. Adam Kemp 发布了关于让用户插入自己的按钮 here,这是我目前尝试实施/修改的方法。不幸的是,我无法访问 Xamarin。

虽然在代码运行时插入了模板,但模板并没有正确更新按钮。如果我在 MyButton Setter 中放置一个断点,我可以看到 value 实际上是一个空按钮,而不是我在主窗口中分配的那个。我该如何解决这个问题?

这是一些简化的代码:

我的模板 UserControl 的 xaml:

<UserControl x:Class="TemplateCode.Template"
     x:Name="TemplatePage"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
     mc:Ignorable="d"
     d:DesignHeight="350"
     d:DesignWidth="525"
     DataContext="{Binding RelativeSource={RelativeSource Self}}"
     Background="DarkGray">

     <Grid>
          <Button x:Name="_button" Width="200" Height="100" Content="Template Button"/>
     </Grid>
</UserControl>

我的模板用户控件背后的代码:

using System.Windows.Controls;

namespace TemplateCode
{
    public partial class Template : UserControl
    {
        public static Button DefaultButton;

        public Template()
        {
             InitializeComponent();
        }

        public Button MyButton
        {
            get
            {
                 return _button;
            }
            set
            {
                _button = value; //I get here, but value is a blank button?!

                // Eventually, I'd like to do something like:
                // Foreach (property in value) 
                // {
                //     If( value.property != DefaultButton.property) )
                //     {
                //         _button.property = value.property;
                //     }
                // }
                // This way users only have to update some of the properties
            }
        }
    }
}

现在是我要使用它的应用程序:

<Window x:Class="TemplateCode.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d"

    xmlns:templateCode="clr-namespace:TemplateCode"

    Title="MainWindow"
    Height="350"
    Width="525"
    Background="LimeGreen"
    DataContext="{Binding RelativeSource={RelativeSource Self}}" >

    <Grid>
        <templateCode:Template>
            <templateCode:Template.MyButton>

                <Button Background="Yellow" 
                    Content="Actual Button"
                    Width="200" 
                    Height="100"/>

            </templateCode:Template.MyButton>
        </templateCode:Template>
    </Grid>
</Window>

现在是背后的代码:

Using System.Windows;
Namespace TemplateCode
{
    Public partial class MainWindow : Window
    {
        Public MainWindow()
        {
            InitializeComponent();
        }
    }
}

编辑:虽然我想删除 template userControl 中不必要的依赖属性,但我仍然想在 button 上设置绑定来自 XAML 的属性。

【问题讨论】:

  • 您也可以创建一个 ObservableCollection 并将其注册为 DependencyProperty。然后使用索引器访问它。否则,尝试使用样式的解决方案,stackoverflow.com/questions/40015997/…
  • “因为这些按钮在另一个控件中,所以很难修改它们”:你能澄清一下吗?每个按钮一个 Style 属性,消费者拥有完全控制权。如果您想共享样式,同时为每个按钮使用不同的模板,您也可以为每个按钮设置一个模板属性。或者只是大量使用 Style.BasedOn。

标签: c# wpf xaml user-controls nested-attributes


【解决方案1】:

而不是使用许多依赖属性,更喜欢样式方法。 Style 包含可用于 Button 控件的所有属性。

我将为 UserControl 中的每个按钮样式创建一个 DependencyProperty。

public partial class TemplateUserControl : UserControl
{
    public TemplateUserControl()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty FirstButtonStyleProperty = 
        DependencyProperty.Register("FirstButtonStyle", typeof (Style), typeof (TemplateUserControl));

    public Style FirstButtonStyle
    {
        get { return (Style)GetValue(FirstButtonStyleProperty); }
        set { SetValue(FirstButtonStyleProperty, value); }
    }

    public static readonly DependencyProperty SecondButtonStyleProperty =
        DependencyProperty.Register("SecondButtonStyle", typeof (Style), typeof (TemplateUserControl));

    public Style SecondButtonStyle
    {
        get { return (Style)GetValue(SecondButtonStyleProperty); }
        set { SetValue(SecondButtonStyleProperty, value); }
    }
}

然后为按钮修改 xaml 以选择这些样式:

<UserControl x:Class="MyApp.TemplateUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="200" d:DesignWidth="300"
             Background="DarkGray">
    <StackPanel>
        <Button x:Name="_button" Width="200" Height="100" 
                Style="{Binding Path=FirstButtonStyle, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
        <Button x:Name="_button2" Width="200" Height="100"
                Style="{Binding Path=SecondButtonStyle, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    </StackPanel>
</UserControl>

现在需要自定义按钮时,可以通过自定义样式来实现:

<StackPanel>
    <StackPanel.Resources>
        <!--common theme properties-->
        <Style TargetType="Button" x:Key="TemplateButtonBase">
            <Setter Property="FontSize" Value="18"/>
            <Setter Property="Foreground" Value="Blue"/>
        </Style>

        <!--unique settings of the 1st button-->
        <!--uses common base style-->
        <Style TargetType="Button" x:Key="BFirst" BasedOn="{StaticResource TemplateButtonBase}">
            <Setter Property="Content" Value="1st"/>
        </Style>

        <Style TargetType="Button" x:Key="BSecond" BasedOn="{StaticResource TemplateButtonBase}">
            <Setter Property="Content" Value="2nd"/>
        </Style>
    </StackPanel.Resources>

    <myApp:TemplateUserControl FirstButtonStyle="{StaticResource BFirst}" 
                               SecondButtonStyle="{StaticResource BSecond}"/>
</StackPanel>

【讨论】:

    【解决方案2】:

    您可以在 UserControl 上注册一个依赖属性 Button 并在其 PropertyChangedCallback 中处理初始化。

    Template.xaml.cs

    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Collections.Generic;
    using System.Windows.Markup.Primitives;
    
    namespace TemplateCode
    {
        public partial class Template : UserControl
        {
            public Template()
            {
                InitializeComponent();
            }
    
            public static readonly DependencyProperty ButtonProperty =
                DependencyProperty.Register("Button", typeof(Button), typeof(Template),
                    new UIPropertyMetadata(new PropertyChangedCallback(ButtonChangedCallback)));
    
            public Button Button
            {
                get { return (Button)GetValue(ButtonProperty); }
                set { SetValue(ButtonProperty, value); }
            }
    
            public static List<DependencyProperty> GetDependencyProperties(Object element)
            {
                List<DependencyProperty> properties = new List<DependencyProperty>();
                MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
                if (markupObject != null)
                {
                    foreach (MarkupProperty mp in markupObject.Properties)
                    {
                        if (mp.DependencyProperty != null)
                        {
                            properties.Add(mp.DependencyProperty);
                        }
                    }
                }
                return properties;
            }
    
            private static void ButtonChangedCallback(object sender, DependencyPropertyChangedEventArgs args)
            {
                // Get button defined by user in MainWindow
                Button userButton     = (Button)args.NewValue;
                // Get template button in UserControl
                UserControl template  = (UserControl)sender;
                Button templateButton = (Button)template.FindName("button");
                // Get userButton props and change templateButton accordingly
                List<DependencyProperty> properties = GetDependencyProperties(userButton);
                foreach(DependencyProperty property in properties)
                {
                    if (templateButton.GetValue(property) != userButton.GetValue(property))
                    {
                        templateButton.SetValue(property, userButton.GetValue(property));
                    }
                }
            }
        }
    }
    

    Template.xaml

    UserControlDataContext继承自parent,不需要显式设置

    <UserControl x:Class="TemplateCode.Template"
         x:Name="TemplatePage"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="350"
         d:DesignWidth="525"
         Background="DarkGray">
    
        <Grid>
            <Button x:Name="button" Width="200" Height="100" Content="Template Button"/>
        </Grid>
    </UserControl>
    

    MainWindow.xaml

    你设置的是Button.Content而不是Button

    <Window x:Class="TemplateCode.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        mc:Ignorable="d"
    
        xmlns:templateCode="clr-namespace:TemplateCode"
    
        Title="MainWindow"
        Height="350"
        Width="525">
        <Window.Resources>
            <Button x:Key="UserButton" 
                    Background="Yellow" 
                    Content="Actual Button"
                    Width="200" 
                    Height="100"
                    />
        </Window.Resources>
        <Grid>
            <templateCode:Template Button="{StaticResource UserButton}"/>
        </Grid>
    </Window>
    

    编辑 - 绑定 Button.Content

    三种方法:

    1.依赖属性

    迄今为止最好的方法。为Button 上的每个属性创建UserControl DP 肯定是矫枉过正,但对于那些想要绑定到ViewModel / MainWindow DataContext 的人来说,这是有意义的。

    Template.xaml.cs

    中添加
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(Template));
    
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
    

    Template.xaml

    <UserControl x:Class="TemplateCode.Template"
    
         ...
    
         DataContext="{Binding RelativeSource={RelativeSource Self}}">
        <Grid>
            <Button x:Name="button" Width="200" Height="100" Content="{Binding Text}"/>
        </Grid>
    </UserControl>
    

    MainWindow.xaml

    <Window.Resources>
        <Button x:Key="UserButton" 
                Background="Yellow" 
                Width="200" 
                Height="100"
                />
    </Window.Resources>
    <Grid>
        <templateCode:Template 
            Button="{StaticResource UserButton}" 
            Text="{Binding DataContext.Txt, 
                           RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
    
    </Grid>
    

    或者

    <Window.Resources>
        <Button x:Key="UserButton" 
                Background="Yellow" 
                Content="Actual Button"
                Width="200" 
                Height="100"
                />
    </Window.Resources>
    <Grid>
        <templateCode:Template 
            Button="{StaticResource UserButton}"/>
    </Grid>
    

    值优先级:UserButton Content > DP Text,因此在 Resources 中设置 Content 即可。

    2.在 ViewModel 中创建按钮

    MVVM 纯粹主义者不会喜欢这样,但您可以使用 Binding 标记而不是 StaticResource

    MainWindow.xaml

    <Grid>
        <templateCode:Template 
            Button="{Binding DataContext.UserButton, 
                             RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
    </Grid>
    

    3.在代码中设置绑定

    正如您已经注意到的,由于所有内容的初始化顺序,无法在 Resources 中引用 ViewModel 属性(例如 Txt)。稍后您仍然可以在代码中执行此操作,但是要证明的错误会有点混乱。

    System.Windows.Data 错误:4:找不到绑定源 参考'RelativeSource FindAncestor, AncestorType='System.Windows.Window',AncestorLevel='1''。 BindingExpression:Path=DataContext.Txt;数据项=空;目标元素 是'按钮'(名称='');目标属性是“内容”(类型“对象”)

    请注意,您需要在 Content 属性上定义完整路径(不能在父级上设置 DataContext)。

    MainWindow.xaml

    <Window.Resources>
        <Button x:Key="UserButton" 
                Background="Yellow" 
                Width="200" 
                Height="100"
                Content="{Binding DataContext.Txt, 
                                  RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                />
    </Window.Resources>
    <Grid>
        <templateCode:Template Button="{StaticResource UserButton}"/>
    </Grid>
    

    Template.xaml.cs

    private static void ButtonChangedCallback(object sender, DependencyPropertyChangedEventArgs args)
    {
        // Get button defined by user in MainWindow
        Button userButton = (Button)args.NewValue;
        // Get template button in UserControl
        UserControl template = (UserControl)sender;
        Button templateButton = (Button)template.FindName("button");
        // Get userButton props and change templateButton accordingly
        List<DependencyProperty> properties = GetDependencyProperties(userButton);
        foreach (DependencyProperty property in properties)
        {
        if (templateButton.GetValue(property) != userButton.GetValue(property))
            templateButton.SetValue(property, userButton.GetValue(property));
        }
        // Set Content binding
        BindingExpression bindingExpression = userButton.GetBindingExpression(Button.ContentProperty);
        if (bindingExpression != null)
            templateButton.SetBinding(Button.ContentProperty, bindingExpression.ParentBinding);
    }
    

    【讨论】:

    • 是否可以在 Windows.Resources 部分的按钮上设置绑定?我玩了一下,但是当我尝试绑定内容时,它只显示一个空白的黄色按钮。不过这看起来真的很好。
    • 我尝试将 'templateButton.GetBinding(property, GetBinding(userButton, property).ParentBinding' 插入 buttonChangedCallback,如 here 所示,但这似乎不起作用。
    • @bwall 更新了我的答案。
    【解决方案3】:

    如果您可以将对按钮的更改分组到数据上下文中的一个或多个属性,则可以使用 DataTriggers:

    <Button x:Name="TestButton">
        <Button.Style>
            <Style>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsButtonEnabled}" Value="True">
                        <Setter TargetName="TestButton" Property="Background" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
    

    您甚至可以在 MultiDataTriggers 中使用多个条件。

    【讨论】:

    • 感谢您回复@lhildebrandt!将一堆属性绑定到几个变量是一个有趣的想法。在这种情况下,我基本上想设置它,以便如果有人摆弄 set any 属性,他们可以,而不必费心创建新的依赖属性,所以我可能无法对它们进行分组.但是感谢您显示样式选项!
    【解决方案4】:

    主要问题是模板组件是在主窗口组件之前初始化的。我的意思是主窗口中按钮的所有属性都是在模板类中的按钮初始化之后设置的。因此,正如您所说,值设置为空。我想说的是关于初始化对象的序列。如果你用下面这样的方式做一个技巧;

    public partial class Template : UserControl
    {
        private Button _btn ;
    
        public Template()
        {
    
        }
    
        public Button MyButton
        {
            get
            {
                return _button;
            }
            set
            {
                _btn = value;
                _button = value;
            }
        }
        protected override void OnInitialized(EventArgs e)
        {
            InitializeComponent();
            base.OnInitialized(e);
    
            this._button.Content = _btn.Content;
            this._button.Background = _btn.Background;
            this.Width = _btn.Width;
            this.Height = _btn.Height;
        }
    }
    

    毫无疑问,它会起作用。

    【讨论】:

      【解决方案5】:

      基于@Funk 答案的另一个选项是在模板上制作内容控件而不是按钮,然后在后面的代码中将内容控件的内容绑定到您的 ButtonProperty:

      在模板上:

      <ContentControl Content={Binding myButton} Width="200" Height="100"/>
      

      在后面的模板代码中:

      public static readonly DependencyProperty myButtonProperty =
              DependencyProperty.Register("Button", typeof(Button), typeof(Template),
                  new UIPropertyMetadata(new PropertyChangedCallback(ButtonChangedCallback)));
      

      然后在主窗口上:

      <Window.Resources>
          <Button x:Key="UserButton" 
                  Background="Yellow" 
                  Content="Actual Button"
                  />
      </Window.Resources>
      <Grid>
          <templateCode:Template myButton="{StaticResource UserButton}"/>
      </Grid>
      

      这样做的好处是 Visual Studio 足够智能,可以在设计时显示此代码,并且总体上代码更少。

      您可以在内容控件或默认样式中为您的按钮设置固定的东西(如位置、字体和颜色),然后只修改按钮所需的部分。

      【讨论】:

        【解决方案6】:

        一种选择是使用

        在 xaml 页面上简单地开始编写 C#

        在 Main Window.xaml 中,您更改为:

        <templateCode:Template x:Name="test">
            <x:Code><![CDATA[
                Void OnStartup()
                {
                    test.MyButton.Content="Actual Button";
                    test.MyButton.Background = new SolidColorBrush(Color.FromArgb(255,255,255,0));
                }
                ]]>
            </x:Code>
        

        然后在 Initialize Object() 之后立即调用 OnStartup()。

        虽然这确实允许您在 xaml 中编辑特定属性,但这与在后面的代码中编写代码大致相同,其他人期望它是这样的。

        【讨论】:

          猜你喜欢
          • 2016-08-08
          • 1970-01-01
          • 2017-02-09
          • 1970-01-01
          • 2019-05-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多