我正在使用WPF自定义控件
I'm having a WPF Custom Control
<local:SuperControl> <local:SuperControl.SBItem> <MultiBinding StringFormat="{}Name: {0} ({1})"> <Binding Path="Name" /> <Binding Path="ID" /> </MultiBinding> </local:SuperControl.SBItem> </local:SuperControl>ViewModel属性
The ViewModel Property
public string Name { get; set; } public string ID { get; set; }考虑物业价值
Name = "John"; ID = "STK001";自定义控件
public class SuperControl : ItemsControl { public static readonly DependencyProperty SBItemProperty = DependencyProperty.Register("SBItem", typeof(string), typeof(BAutoComplete), new PropertyMetadata(null)); public string SBItem { get { return (string)GetValue(SBItemProperty); } set { SetValue(SBItemProperty, value); } } public override void OnApplyTemplate() { string Name = SBItem; string ID = SBItem; string StringFormat = SBItem; } }考虑自定义控件中的代码段
Consider the Piece of Code in the Custom Control
public override void OnApplyTemplate() { string Name = SBItem; string ID = SBItem; string StringFormat = SBItem; }在这里,我需要获取绑定属性的值 名称, ID 和字符串格式 strong>依赖性属性 SBItem 。
Here I need to get the Value of the Binded Property Name, ID and String Format from the Dependency Property SBItem. Kindly assist me.
推荐答案您无法在 ApplyTemplate 方法中获得绑定值。
You cannot get Binded values in ApplyTemplate method. As it is called before binding.
因此,请使用 new PropertyMetadata(null,new PropertyChangedCallback(OnPropertyChanged))为属性更改提供回调。
So, provide a callback for property change using new PropertyMetadata(null,new PropertyChangedCallback(OnPropertyChanged)) in your DP definition.
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { string value = (string)e.NewValue; string Name = value.Split(new char[] { ':' })[1].Split(new char[] { '(' })[0].Trim(); string ID = value.Split(new char[] { ':' })[1].Split(new char[] { '(' })[1].Split(new char[] { ')' })[0].Trim(); string formatting = BindingOperations.GetMultiBinding(d, MyButton.MyPropertyProperty).StringFormat; }更多推荐
在WPF C#的依赖属性中查找绑定属性的列表
发布评论