开发者

WPF Custom Control - Binding a template item to a Path

In a WPF Custom Control template, is there any way that I can do the following in XAML?:

var selItemText = this.GetTemplateChild("PART_SelectedItemText") as TextBlock;
var binding = new Binding("SelectedItem.开发者_开发问答" + DisplayMemberPath);
binding.RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent);
selItemText .SetBinding(TextBlock.TextProperty, binding);

Note that the interesting part of this statement is the binding constructor - I am building up a path based on both some text I specify ("SelectedItem."), and the path provided by the user.

The consumer would use the control similar to:

<c:MyControl DisplayMemberPath="Description" />


short answer: no, it's not possible to get this entirely in xaml within the controltemplate

your possibilities are:

  • use what you have (possibly using attached properties / a behavior to make it more MVVM-like)
  • use a MultiBinding one binding to the "SelectedItem" the other to "DisplayMemberPath" and your MultiValueConverter using Reflection to reflect down the DisplayMemberPath (may be a bit ugly)
  • create a class that inherits from Binding and exposes Properties that you can bind the DisplayMemberPath to and changes the underlying Binding (read here for how you can do this) (complicated)
  • use Reflection to instantiate a MS.Internal.Data.DisplayMemberTemplateSelector / build something similar
  • think about if your design is right. Other than your Control being some kind of ItemsControl (if that was the case you should inherit from ItemsControl and use the DisplayMemberPath you get there), I don't see why you shouldn't use a Binding on the outside like <c:MyControl DisplayMember="{Binding SelectedItem.Description}" /> and in your ControlTemplate use a TemplateBinding to bind to "DisplayMember"


You can split it to two different bindings. Have SelectedItem binds to a toplevel control of TextBlock and TextBox.Text bind to DisplayMemberPath as TemplateBinding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜