2

I am relatively new to WPF and really like the possibility to do to GUI logic in the markup. Currently, I have a control which I only want to be visible, if another control is visible.

<AttachedControl IsVisible="{x:Reference Name=mainControl}"/>
<MasterControl Name="mainControl" IsVisible="True">
...
</MasterControl>

When I am using this, it is working in the designer, but produces the error message:

Error "" is no valid value for the property "IsVisible". ProjectX MyUserControl.xaml

It also compiles successfully and I can run the app. So can anybody tell me where is the problem or what I am doing/understanding wrong?

  • 3
    You probably want to use data binding: `IsVisible="{Binding IsVisible, ElementName=mainControl}"`. – Clemens Jun 11 '19 at 08:57
  • Even though I am not yet understanding, it is working. :) –  Jun 11 '19 at 08:59
  • It's not a good idea to start coding WPF/XAML without understanding the basic concepts. Probably read some introductory material. E.g. *WPF Unleashed* by Adam Nathan, a really good book. – Clemens Jun 11 '19 at 09:02
  • That's what this project is about. Starting with WPF. ;) –  Jun 11 '19 at 09:09

1 Answers1

0

The x:Reference markup extension refers to an element's x:Name but you cannot bind the IsVisible property to the control with the x:Name "mainControl" itself. You should bind to a boolean property of it.

This should work provided that mainControl has an IsVisible property, i.e. the x:Reference is the source of the binding and IsVisible is the path:

<AttachedControl IsVisible="{Binding IsVisible, Source={x:Reference Name=mainControl}}"/>

You can also bind to another element by setting the ElementName property of the binding:

<AttachedControl IsVisible="{Binding IsVisible, ElementName=mainControl}"/>

What is the difference between x:Reference and ElementName?

mm8
  • 163,881
  • 10
  • 57
  • 88