我花了整个早上看相关帖子,但我发现没有任何一篇文章涉及到我正在经历的确切问题,尽管在这个过程中我学到了更多。
(在WPF中使用MVVM和用户控件)
场景:我需要创建一个可重用的控件,它是一个数据网格,根据表单要求显示两列或三列。我已经创建了一个自定义控件,并且有一个依赖属性来隐藏/显示第三列选项:
*注意:这种可见性完全取决于我设置的属性,我从不需要它根据其他区域的选择而改变。
现在当我使用这个控件时:
(在WPF中使用MVVM和用户控件)
场景:我需要创建一个可重用的控件,它是一个数据网格,根据表单要求显示两列或三列。我已经创建了一个自定义控件,并且有一个依赖属性来隐藏/显示第三列选项:
*注意:这种可见性完全取决于我设置的属性,我从不需要它根据其他区域的选择而改变。
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);
}
}
}
这里是xaml.Generic:
<CheckBoxColumn Binding="{Binding StuffInThirdColumn}"
Header="ThirdColumn"
Visibility="{Binding DisplayThirdColumn,
Converter={StaticResource BooleanToVisibilityConverter},RelativeSource={RelativeSource TemplatedParent}}"/>
现在当我使用这个控件时:
<MyControls:MyCustomControl DisplayThirdColumn="False"/>
非常抱歉,如果我的“新手”表现显而易见的话。但是我这里是否遗漏了某些明显的东西呢?当我在控件xaml.Generic上显式设置可见性属性为Collapsed时,它会正确地隐藏列:
<CheckBoxColumn Visibility="Collapsed"..../>
输出窗口似乎表明找不到要应用的元素。
如果我不能使用相对源,你知道我可以通过其他方式实现这个吗?
System.Windows.Data Error: 2 : 无法为目标元素找到控制 FrameworkElement 或 FrameworkContentElement。BindingExpression:Path=DisplayThirdColumn; DataItem=null; target element is 'CheckBoxColumn' (HashCode=19379515); target property is 'Visibility' (type 'Visibility')