I've spent the morning looking at related posts, NONE of them I've found address the exact issue I'm experiencing, although I've learned a bit more along the way.
(Using MVVM with user controls in WPF)
Scenario: I need to create a re-usable control which is a datagrid that shows two or three columns depending on the form requirements. I have a custom control I've already created, as well as a dependency property for hiding / showing this third column option:
*Note: This visibility is dependent entirely on what I set the property to, I never need it to change based off of selection in other areas.
public class MyCustomControl: Control
{
public static readonly DependencyProperty DisplayThirdColumnProperty = DependencyProperty.Register(
"DisplayThirdColumn",
typeof(bool),
typeof(MyCustomControl),
new FrameworkPropertyMetadata(false));
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
/// <summary>
/// Gets or sets a value indicating whether the the third column should display.
/// </summary>
public bool DisplayThirdColumn
{
get
{
return (bool)this.GetValue(DisplayThirdColumnProperty);
}
set
{
this.SetValue(DisplayThirdColumnProperty, value);
}
}
}
Here is the xaml.Generic:
<CheckBoxColumn Binding="{Binding StuffInThirdColumn}"
Header="ThirdColumn"
Visibility="{Binding DisplayThirdColumn,
Converter={StaticResource BooleanToVisibilityConverter},RelativeSource={RelativeSource TemplatedParent}}"/>
Now when I consume the control:
<MyControls:MyCustomControl DisplayThirdColumn="False"/>
My apologies if my 'newbieness' is showing, but am I missing something obvious here? When I set the Visiblity property to collapsed explicitly on the control xaml.Generic, it correctly hides the column:
<CheckBoxColumn Visibility="Collapsed"..../>
Output window seems to indicate that it cant find the element to apply it to.
If I can't use relative source, do you know another way I can accomplish this?
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=DisplayThirdColumn; DataItem=null; target element is 'CheckBoxColumn' (HashCode=19379515); target property is 'Visibility' (type 'Visibility')