Below is the complete code for the example. I have a user control called ColorPicker that contains 3 buttons each displaying a color. When a button is clicked the Color property in the CurrentSettings class is set. What I want to happen is the color of the rectangle on MainPage to change to match the new CurrentSettings.Color and the color of the rectangles (added in the code behind) in the listbox in the second user control to also change color to match the new CurrentSettings.Color.
I have been trying to accomplish this unsuccessfully using Dependency Properties and INotifyPropertyChanged and have now decided to start again with a clean slate.
// Current Sttings class:
public static class CurrentSettings
{
public static Color Color { get; set; }
}
// MainPage XAML
<Grid x:Name="LayoutRoot">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="33*"/>
<ColumnDefinition Width="33*"/>
<ColumnDefinition Width="33*"/>
</Grid.ColumnDefinitions>
<local:ColorPicker/>
<Rectangle Grid.Column="1" Name="rec" Width="160" Height="80" Fill="Yellow"/>
<local:PenSelector Grid.Column="2"/>
</Grid>
// ColorPicker User Control XAML:
<StackPanel x:Name="LayoutRoot" Orientation="Horizontal">
<Button x:Name="Red" Width="40" Height="40" Click="Red_Click">
<Button.Content>
<Rectangle Width="30" Height="30" Fill="Red"/>
</Button.Content>
</Button>
<Button x:Name="Green" Width="40" Height="40" Click="Green_Click">
<Button.Content>
<Rectangle Width="30" Height="30" Fill="Green"/>
</Button.Content>
</Button>
<Button x:Name="Blue" Width="40" Height="40" Click="Blue_Click">
<Button.Content>
<Rectangle Width="30" Height="30" Fill="Blue"/>
</Button.Content>
</Button>
</StackPanel>
// ColorPicker User Control Code Behind:
public partial class ColorPicker : UserControl
{
public ColorPicker()
{
InitializeComponent();
}
private void Red_Click(object sender, RoutedEventArgs e)
{
CurrentSettings.Color = Colors.Red;
}
private void Green_Click(object sender, RoutedEventArgs e)
{
CurrentSettings.Color = Colors.Green;
}
private void Blue_Click(object sender, RoutedEventArgs e)
{
CurrentSettings.Color = Colors.Blue;
}
}
// Pen Selector User Control XAML:
<ListBox x:Name="LayoutRoot"/>
// Pen Selector User Control XAML Code Behind:
public partial class PenSelector : UserControl
{
public PenSelector()
{
InitializeComponent();
LayoutRoot.Items.Add(new Rectangle() { Width = 160, Height = 80, Fill = new SolidColorBrush(Colors.Yellow) });
LayoutRoot.Items.Add(new Rectangle() { Width = 160, Height = 80, Fill = new SolidColorBrush(Colors.Yellow) });
}
}
You were on the right track with
INotifyPropertyChanged. Start with the settings class but make the Color setting an instance property on a class that implementsINotifyPropertyChanged.Now place an instance of this in the Resources your
App.Xaml:-Now add a
CurrentSettingsprivate property to your color picker:-Finally use binding on the rectangle
Fillproperty like this:-