Alright so I want to bind the Foreground property of a TextBlock control to a property in the codebehind of the MainWindow. The control is on a page which is loaded in a frame on the MainWindow. I have tried a few things, but the binding I would think should work, as demonstrated, does not.
The mainwindow and Page xaml:
<MainWindow>
<Frame></Frame>
</MainWindow>
<Page>
<TextBlock Foreground="{Binding RelativeSource={
RelativeSource FindAncestor, AncestorType={
x:Type local:MainWindow}}, Path=TextBrush}" />
<!-- or Foreground="{Binding TextBrush, RelativeSource={
RelativeSource FindAncestor, AncestorType={
x:Type local:MainWindow}}}" /> -->
</Page>
And the mainwindow codebehind:
public partial class MainWindow : INotifyPropertyChanged {
private Brush _textBrush;
public Brush TextBrush
{
get => _textBrush;
set
{
_textBrush = value;
OnPropertyChanged("TextBrush");
}
}
public ICommand SwitchToDarkmodeCommand
{
get
{
return new DelegateCommand(() =>
{
TextBrush = Brushes.White;
BackgroundBrush = (Brush)new BrushConverter().ConvertFromString("#D2D2D2");
});
}
}
It seems way too simple. What am I doing wrong here?
Edit: the output. Good point.
System.Windows.Data Error: 4 : Cannot find source for binding with reference
'RelativeSource FindAncestor, AncestorType='AddINDesignerWPF.MainWindow', AncestorLevel='1''.
BindingExpression:Path=TextBrush; DataItem=null; target element is 'TextBlock' (Name='');
target property is 'Foreground' (type 'Brush')