大家知道在xaml文件中有一种绑定叫TemplateBinding,可以用来将某个属性绑定父级或者自身的另一个属性上而不需要名称。如
<ContentControl
Grid.Column="0"
Height="52"
Margin="0,0,5,0"
Content="{TemplateBinding HeadControl}"
Visibility="{TemplateBinding HeadControl,
Converter={StaticResource Null2VisibilityReConverter}}" />
当我们需要在后台用代码设置Binding时,构建Binding,再绑定到目标控件的目标属性上即可
Binding binding = new Binding($"[{bindName}]");
binding.Mode = BindingMode.OneWay;
TextBlock _textBlock = new TextBlock();
_textBlock.SetBinding(TextBlock.TextProperty,binding);
但是当我们需要在代码中设置TemplateBinding时
Button _button = new Button();
_button.Content = "111";
_button.ContentTemplate = new DataTemplate();
FrameworkElementFactory _Framework = new FrameworkElementFactory(typeof(Border));
FrameworkElementFactory _textBlock = new FrameworkElementFactory(typeof(TextBlock));
Binding _binding = new Binding("Content")
{
RelativeSource = new RelativeSource() { Mode = RelativeSourceMode.TemplatedParent },
Mode = BindingMode.OneWay,
};
_textBlock.SetBinding(TextBlock.TextProperty, _binding);
_Framework.AppendChild(_textBlock);
_button.ContentTemplate.VisualTree = _Framework;
上面这段代码,就是给Button设置了ContentTemplat,里面用一个Border包裹了一个Textblock,这个TextBlock的Text属性,就绑定了父级的Content属性。Button的Content是111,TextBlock的Text就是111.其中New Binding("Content")是简写了Path。构建Binding对象的时候也可以直接New Binding(),后面用Path指定源属性。如果Path没指定,就相当于xaml中的
<TextBlock Text="{Binding }" />
其中RelativeSource设置了绑定的是父级,Mode是绑定的数据流方向