Early start to the new year on SO for me :)
I'm trying to help out a friends with what I thought would be a simple thing. Basically we just want to change a style at runtime in code and update the style for a TextBlock.
I had no problem making this work with any other type of element, except the TextBlock. I'm now very curious if I've missed something here, or if indeed there is a bug. What would be the nicest way to solve this?
The code here is just for demonstration, it works with TextBox but not TextBlock (when targettype etc is changed of course)
Style defined in a resourcedictionary called StandardStyles, under the Common folder
<Style x:Key="textStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="red"/>
<Setter Property="FontFamily" Value="Segoe UI"/>
</Style>
The UI
<StackPanel Orientation="Horizontal">
<ListBox ItemsSource="{Binding Fonts}" Height="300" Width="300" SelectionChanged="ListBox_SelectionChanged_1"></ListBox>
<Border BorderBrush="White" BorderThickness="5" Padding="20,0,0,0" Height="300" Width="300">
<TextBlock Text="Hi here is some text" Style="{Binding FontStyleText}"/>
</Border>
</StackPanel>
The code
public sealed partial class MainPage : INotifyPropertyChanged
{
private Style _fontStyleText;
public Style FontStyleText
{
get
{
return this._fontStyleText;
}
set
{
if (value == this._fontStyleText) return;
this._fontStyleText = value;
NotifyPropertyChanged();
}
}
private List<string> _fonts;
public List<string> Fonts
{
get
{
return this._fonts;
}
set
{
if (value == this._fonts) return;
this._fonts = value;
NotifyPropertyChanged();
}
}
public MainPage()
{
this.InitializeComponent();
DataContext = this;
Fonts = new List<string> {"Segoe UI", "Showcard Gothic", "Arial"};
FontStyleText = Application.Current.Resources["textStyle"] as Style;
}
private void ListBox_SelectionChanged_1(object sender, Windows.UI.Xaml.Controls.SelectionChangedEventArgs e)
{
var font = (sender as ListBox).SelectedItem as string;
var res = new ResourceDictionary()
{
Source = new Uri("ms-appx:///Common/StandardStyles.xaml", UriKind.Absolute)
};
var style = res["textStyle"] as Style;
style.Setters.RemoveAt(0); // if it is the first item otherwise for more accurat removal se below :D
foreach (var item in style.Setters.Cast<Setter>().Where(item => item.Property == FontFamilyProperty))
{
style.Setters.Remove(item);
}
style.Setters.Add(new Setter(FontFamilyProperty, new FontFamily(font)));
style.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush(Colors.Purple)));
FontStyleText = style;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}