WPF 代码设置TemplateBinding

大家知道在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是绑定的数据流方向

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值