WPF Edit Resource

风格不统一 提交于 2019-12-08 02:56:20

问题


Hi is there any way to change a Resource brush from code or via some binding? what I want to do is change the color of my "main" brush when a button is clicked.

Thanks a lot!

Edit:

Its a GradientBrush how do i change the colors on that?

myBrush.GradientStops[0].Color = Colors.Red;

just gives me a exception... and is there any way to animate the color change, like a story board?


回答1:


For animating the change, try creating a Storyboard and calling Begin on it.

(I'll go throw together an example)

edit: Looks like it's another Silverlight != WPF fail on my part. I cant seem to get it going in WPF.




回答2:


If you're using the Model-View-ViewModel (MVVM) pattern or something similar, you could make the brush colour (or the entire brush) a property of your viewmodel and bind directly to it.

In my (inexperienced) opinion, resources shouldnt change at runtime. If it's going to be changing, bind it.

(edit2: Changed from Silverlight-style top-level UserControl to WPF Window. As Ray Booysen noted in the comments, a UserControl in WPF would expose the colour via a DependencyProperty, not have it bound to a ViewModel.)

XAML:

<Grid x:Name="LayoutRoot">
    <Grid.Background>
        <SolidColorBrush Color="{Binding BackgroundColor}" />
    </Grid.Background>
    ...

Viewmodel class:

public class MyViewModel : INotifyPropertyChanged
{
    public Color BackgroundColor
    {
        get { ... }
        set { ... } // fire PropertyChanged event
    }
    ...

XAML.cs:

public partial class MyWindow : Window
{
     private MyViewModel m_viewmodel;

     public MyWindow()
     {
          InitializeComponent();
          viewmodel = new MyViewModel();
          this.LayoutRoot.DataContext = viewmodel;
     }

     private void ButtonClick(object sender, RoutedEventArgs e)
     {
         this.viewmodel.BackgroundColor = Color.Red;
     }
     ...


来源:https://stackoverflow.com/questions/529621/wpf-edit-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!