C# 资源值随按钮更改

C# Resource Value Changed With Button

我有一个简单的 UWP 应用程序和一个简单的计算器。所以我通过这样的样式设置按钮的所有属性。

<Page.Resources>
    <Style TargetType="Button" x:Key="CalculatorButtons">
        <Setter Property="VerticalAlignment" Value="Stretch" />
        <Setter Property="HorizontalAlignment" Value="Stretch" />
        <Setter Property="FontSize" Value="30" />
        <Setter Property="BorderThickness" Value="1" />
        <Setter Property="BorderBrush" Value="Black" />
        <Setter Property="Background" Value="AntiqueWhite" />
    </Style>
</Page.Resources>

我想制作一个按钮来更改我制作的样式中的背景值 属性。我的按钮代码是这样开始的

private void ColorChange_Click(object sender, RoutedEventArgs e)
{

}

我是新手,无法从这里访问和更改它。

您不能在运行时修改样式,唯一的方法是创建新样式并替换旧样式。

private void ColorChange_Click(object sender, RoutedEventArgs e)
{
       var style = new Style(typeof(Button));

        style.Setters.Add(new Setter(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Stretch));
        style.Setters.Add(new Setter(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Stretch));
        style.Setters.Add(new Setter(Control.FontSizeProperty, 30.0));
        style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(1.0)));
        style.Setters.Add(new Setter(Control.BorderBrushProperty, Brushes.Black));

        style.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.Orange));

        this.Resources["CalculatorButtons"] = style;
}

请注意,在这种情况下您必须使用 DynamicResource,例如:

<Button Style="{DynamicResource ResourceKey=CalculatorButtons}" ...

好的,经过大量搜索,我在这里找到了我需要的一切 http://blog.jerrynixon.com/2013/01/walkthrough-dynamically-skinning-your.html 这个想法真的很简单。所以根据我的风格,我删除了背景 setter 并像这样制作了自己的资源。但在它自己的字典中,我将其命名为 Style.Blue.xaml,因为它是蓝色,我为我所有的颜色都做了它,就像杰里尼克松说的那样。

<SolidColorBrush x:Key="ButtonColor" Color="Blue" />

我会在我的按钮中使用此行访问它

Background="{StaticResource ButtonColor}"

之后,我在按钮所在的 MainPage.xaml.cs 中创建了这个。

void ChangeTheme(Uri source)
    {   // Recreated my Merged dictinaries at the app.xaml

        var _Custom = new ResourceDictionary { Source = source };
        var _Main = new ResourceDictionary { MergedDictionaries = { _Custom } };
        App.Current.Resources = _Main;


        // This is needed to basiclly Refresh the page since we use Static Resources.
        // so we navigate forth and back to the whole frame.

        var _Frame = Window.Current.Content as Frame;
        _Frame.Navigate(_Frame.Content.GetType());
        _Frame.GoBack();
    }

然后我在每个按钮上添加了这段代码,并根据我想要的颜色更改了源代码(如果我想要蓝色,它是 -> Style.Blue.xaml for Red -> Style.Red.xaml)和 ms -appx:/StyleColors/ 是路径。我为我所有的样式创建了一个文件夹。

private void ColorChange_Click(object sender, RoutedEventArgs e)
        {
            ChangeTheme(new Uri("ms-appx:/StyleColors/Style.Blue.xaml"));
        }

现在只需一行代码,我就可以更改所有按钮的颜色或我需要的其他类型的数据。

希望也能帮到更多人