【发布时间】:2014-02-25 21:32:39
【问题描述】:
我需要将一些东西绑定到我的 VisualTree 中一个元素的子元素。
在用户控件中:
<StackPanel>
<DataGrid x:Name="dataGrid" />
<Control Tag="{Binding ElementName=dataGrid}" />
</StackPanel>
在 DataGrid 的模板中:
<Template TargetType=DataGrid>
......
<Control x:Name="FindMe" />
......
</Template>
我想做的是遍历 DataGrid 的 VisualTree,为此我创建了一个 自定义标记扩展:
public class TemplatePartBinding : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
Binding binding = new Binding();
binding.ElementName = ElementName;
// HOW DO I GET THE SOURCE OBJECT FROM THE BINDING ?
DataGrid dataGrid = // Extract the DataGrid from the binding.
Control _findMe = VisualTreeHelperExtentions.FindVisualChild<Control>(dataGrid,"FindMe");
binding.Target = _findMe;
binding.Path = new PropertyPath("Tag");
return binding;
}
[ConstructorArgument("ElementName")]
public string ElementName
{
get;
set;
}
[ConstructorArgument("TemplatePartName")]
public string TemplatePartName
{
get;
set;
}
}
在为绑定的 ElementName 值指定名称后,我不想在 ProvideValue 中找到 DataGrid(绑定的源对象),
如何从刚刚创建的绑定中提取 DependencyObject(我的 DataGrid)?
【问题讨论】:
-
你能展示一下你打算如何使用它以及你想绑定什么吗?
-
了解绑定源的唯一方法是使用 BindingOperations.GetBindingExpression 方法从绑定中获取 BindingExpression。但是您只能使用指定的绑定目标来执行此操作,因此它不适用于您的情况。
标签: wpf binding visual-tree