xaml:如何通过路由事件使用自定义控件更改基本元素属性

时间:2014-02-07 13:37:46

标签: c# wpf xaml visual-studio-2012 custom-controls

我在 Generic.xaml 文件中创建了一个自定义控件按钮,并在 CustomControl.cs {{1}中创建了点击路由事件当我在 MainWidow.cs [C# file for custom control button]文件中定义点击事件时,以便在点击按钮时其背景属性会发生变化。

我面临的问题是“On Button click”它的背景属性应该改变但不是。

[C# file for implementing the custom library]

MainWindow.xaml

<Window x:Class="my_ToolBox.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ravi="clr-namespace:my_ToolBox" Title="MainWindow" Height="350" Width="525"> <Grid> <ravi:Button_Primary Text="Primary" x:Name="Primary_button"></ravi:Button_Primary> </Grid></Window>

MainWindow.cs

namespace my_ToolBox { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Primary_button.onclick+=Primary_button_onclick; } private static void Primary_button_onclick(object sender, RoutedEventArgs e) { MessageBox.Show("Hello robins"); Button_Primary btn = new Button_Primary(); btn.Background = new SolidColorBrush(Color.fromRgb(0,0,0)); } } }

Generic.xaml

<Style TargetType="{x:Type local:Button_Primary}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:Button_Primary}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" > <Button Height="38" Width="86" Background="#428bca" BorderBrush="#428bca" BorderThickness="0" Content="{TemplateBinding Text}" FontSize="14" Foreground="white" FontFamily="Segoe UI" x:Name="Primary_button"> </Button> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style>

CustomControl.cs

1 个答案:

答案 0 :(得分:1)

啊,我发现了你的问题...我很抱歉,但这也是真正的基本问题:

private static void Primary_button_onclick(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Hello robins");
    Button_Primary btn = new Button_Primary();
    btn.Background = new SolidColorBrush(Color.fromRgb(0,0,0));
}

在这里,您创建一个新的Button_Primary对象并设置 Background属性,而不是您的UI元素的Background

Button_Primary btn = new Button_Primary();
btn.Background = new SolidColorBrush(Color.fromRgb(0,0,0));

您需要做的就是从UI访问实际的 Button_Primary对象...您是如何做到的?好吧,您可以在MSDN上的How to: Find ControlTemplate-Generated Elements页面上找到完整的故事,但其要点是:您需要一个应用了相关ControlTemplate的控件实例< / em>然后您只需使用FrameworkTemplate.FindName Method即可访问Button