【发布时间】:2015-08-23 08:05:55
【问题描述】:
我花了一上午的时间查看相关帖子,但我发现没有一篇能解决我遇到的确切问题,尽管我在此过程中学到了更多东西。
(在 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 上将 Visiblity 属性显式设置为折叠时,它正确地隐藏了该列:
<CheckBoxColumn Visibility="Collapsed"..../>
输出窗口似乎表明它找不到要应用它的元素。
如果我不能使用相对来源,你知道我可以用另一种方法吗?
System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。绑定表达式:路径=DisplayThirdColumn;数据项=空;目标元素是“CheckBoxColumn”(HashCode=19379515);目标属性是“可见性”(类型“可见性”)
【问题讨论】:
-
列不在同一个可视化树中,因此不能继承DataContext。您可以在这里寻找解决方案:stackoverflow.com/questions/22073740/…
标签: c# wpf binding visibility