Set control Background color using Dynamic Resource in WPF?

前端 未结 3 899
旧时难觅i
旧时难觅i 2020-12-03 10:29

This is my XAML


            

3条回答
  •  盖世英雄少女心
    2020-12-03 10:52

    To gain access to the Resource of the code must identify them in the file App.xaml:

    
        
    
    

    XAML example

           
        

    The Resource can be changed in code line of the form:

    Application.Current.Resources["MyResource"] = MyNewValue;
    

    Example:

    Code behind

    // using ContentRendered event
    private void Window_ContentRendered(object sender, EventArgs e)
    {
        SolidColorBrush MyBrush = Brushes.Aquamarine;
    
        // Set the value
        Application.Current.Resources["DynamicBG"] = MyBrush;         
    }
    
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        SolidColorBrush MyBrush = Brushes.CadetBlue;
    
        // Set the value
        Application.Current.Resources["DynamicBG"] = MyBrush;
    }
    

    Principle, DynamicResources were designed, so they can be changed. Where to change - it is the task of the developer. In the case of Color, it is one of the most common methods. See the MSDN, for more information.

    P. S. I recommend using App.xaml, because there have been cases where a StaticResource has been used successfully, but not DynamicResource (resources are placed in the Window.Resources). But after moving the resource in App.xaml, everything started to work.

提交回复
热议问题