“What happens if we replace a
specific resource? Would that be reflected in all objects using the resource? And if not, can webind to the resource dynamically?”接上篇博文,如果我们需要在C#代码中动态替换某个logical resource,我们该如何做呢?
如,Window的Resources属性赋值如下:
Button Click事件中Replace Window的key为"brush1"的Resources
private void OnReplaceBrush(object sender, RoutedEventArgs e) { var brush = new LinearGradientBrush(); brush.GradientStops.Add(new GradientStop(Colors.Pink, 0.2)); brush.GradientStops.Add(new GradientStop(Colors.Blue, 0.5)); brush.GradientStops.Add(new GradientStop(Colors.Violet, 0.8)); this.Resources["brush1"] = brush; }
点击按钮,程序没有任何反应,可以通过DynamicResource这个markup extension实现。
“Run the application and click on the button. You'll notice nothing happens. Now
change the StaticResource markup extension to DynamicResource on theRectangle:”点击Button后:
附XAML和C#代码:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace DynamicallyBindingToALogicalResource{ ////// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void OnReplaceBrush(object sender, RoutedEventArgs e) { var brush = new LinearGradientBrush(); brush.GradientStops.Add(new GradientStop(Colors.Pink, 0.2)); brush.GradientStops.Add(new GradientStop(Colors.Blue, 0.5)); brush.GradientStops.Add(new GradientStop(Colors.Violet, 0.8)); this.Resources["brush1"] = brush; } }}