I am trying to use the IsHighlighted dependency property on the CustomView class. It works as expected when I pass it a hard bool value, but it doesnt work when I pass it a binding. Anyone know why?
Also should I be calling OnPropertyChanged in the IsHighlighted setter?
MainWindow.xaml
<StackPanel>
<!-- The data context is set properly -->
<TextBlock Text="{Binding Text}" FontSize="50"/>
<!-- This works! -->
<views:CustomView IsHighlighted="true"/>
<!-- This does not! -->
<views:CustomView IsHighlighted="{Binding Path=One}"/>
</StackPanel>
MainWindowViewModel.cs
public class MainWindowViewModel : ViewModelBase
{
private string _text;
public string Text
{
get { return _text; }
set { _text = value; }
}
private bool _one;
public bool One
{
get { return _one; }
set { _one = value; }
}
public MainWindowViewModel()
{
Text = "bound text!";
One = true;
}
}
CustomView.xaml
<UserControl>
<Grid Background="{Binding Path=CurrentBackground,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type local:CustomView}, AncestorLevel=1}}">
<TextBlock Text="{Binding IsHighlighted}" FontSize="40"/>
</Grid>
</UserControl>
CustomView.xaml.cs
public partial class CustomView : UserControl
{
public CustomView()
{
InitializeComponent();
DataContext = this;
}
public static readonly DependencyProperty IsHighlightedProperty =
DependencyProperty.Register(
name: "IsHighlighted",
propertyType: typeof(bool),
ownerType: typeof(CustomView)
);
public bool IsHighlighted
{
get => (bool)GetValue(IsHighlightedProperty);
set => SetValue(IsHighlightedProperty, value);
}
public Brush CurrentBackground
{
get
{
if (IsHighlighted)
return new SolidColorBrush(Colors.Yellow); // highlighted
else
return new SolidColorBrush(Colors.White); // not highlighted
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
}