Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

動的バインディング

アプリ実行

起動


ボタンクリック


ソースコード

App.xaml
<Application x:Class="HelloWorld.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
</Application>
MainWindow.xaml
<Window x:Class="HelloWorld.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="100" Width="150">
    <Window.Resources>
        <SolidColorBrush x:Key="toShare">Yellow</SolidColorBrush>
    </Window.Resources>
    <StackPanel>
        <!-- 更新しない場合は、StaticResourceでよい。 -->
        <Button Background="{DynamicResource toShare}" Click="Button_Click">ボタン1</Button>
    </StackPanel>
</Window>
MainWindow.xaml.cs
using System.Windows;
using System.Windows.Media;

namespace HelloWorld {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e) {
            Brush newBrush = new SolidColorBrush(Colors.Blue);
            this.Resources["toShare"] = newBrush;
        }
    }
}