WPF Binding a visual brush's visual to a different window
Asked Answered
M

1

5

I need a rectangle in my settings window to display a scaled down version of of the main window. This is the non-working code that I have right now. Is it possible to do what I want to do?

<Rectangle.Fill>
<VisualBrush Stretch="Uniform" Visual="{Binding ElementName=local:MainWindow}" />
</Rectangle.Fill>
Mcdaniel answered 4/4, 2010 at 0:28 Comment(0)
M
7

Yes, but not in pure XAML and not using ElementName. Instead, you'll need to pass a reference to the main window into your settings window. You can then bind the VisualBrush.Visual to that reference.

As a simplified example, when creating your settings window, you could set its DataContext to the main window:

// MainWindow.xaml.cs
SettingsWindow w = new SettingsWindow { DataContext = this };
w.Show();

Then the SettingsWindow you could access the MainWindow as {Binding} (because the MainWindow is now the SettingsWindow's DataContext, and {Binding} refers to the DataContext):

<!-- SettingsWindow.xaml -->
<Rectangle.Fill>
  <VisualBrush Stretch="Uniform" Visual="{Binding}" />
</Rectangle.Fill>

In practice you probably won't want to pass the main window object as the DataContext because that's too blunt an instrument, but hopefully this gives you the idea.

Meek answered 4/4, 2010 at 1:13 Comment(2)
Noob question, but what do you mean by "you probably won't want to pass the main window object as the DataContext because that's too blunt an instrument"? What should I pass?Mcdaniel
The problem is that if you set the DataContext to the MainWindow, you can't set anything else as the DataContext. Specifically, since your Settings window probably wants to be binding to some kind of settings object, you'll probably want the settings object to be the DataContext... or at least part of the DataContext. The idiomatic solution in WPF is to create a "view model" class that contains all the info needed for the view (in this case the MainWindow visual and the settings object(s)), and set the DataContext to this "view model." Hope that makes a bit more sense now!Meek

© 2022 - 2024 — McMap. All rights reserved.