WPF:绑定到继承用户控件基类的类的依赖项属性
本文关键字:依赖 属性 基类 控件 绑定 继承 用户 WPF | 更新日期: 2023-09-27 17:56:42
我在wpf中有一个名为"GoogleMap.xaml/.cs"的用户控件,其中xaml声明的开头如下所示:
<controls:BaseUserControl x:Class="CompanyNamespace.Controls.GoogleMap"
背后的代码:
public partial class GoogleMap : BaseUserControl{
public static readonly DependencyProperty MapCenterProperty =
DependencyProperty.Register("MapCenter", typeof(string), typeof(GoogleMap), new FrameworkPropertyMetadata(string.Empty, OnMapCenterPropertyChanged));
public string MapCenter {
get { return (string)GetValue(MapCenterProperty); }
set { SetValue(MapCenterProperty, value); }
}
private static void OnMapCenterPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e){
GoogleMap control = source as GoogleMap;
control.SetCenter(e.NewValue.ToString());
}
...
}
我能够从GoogleMap.xaml寻址该属性的正确语法是什么:
MapCenter="{Binding Location}"
如果我将属性放在 BaseUserControl 类中,我只能从 GoogleMap.xaml 绑定到此属性。
更新谷歌地图视图模型.cs
public class GoogleMapViewModel : ContainerViewModel{
private string location;
[XmlAttribute("location")]
public string Location {
get {
if (string.IsNullOrEmpty(location))
return appContext.DeviceGeolocation.Location();
return ExpressionEvaluator.Evaluate(location);
}
set {
if (location == value)
return;
location = value;
RaisePropertyChanged("Location");
}
}
为了将用户控件的属性绑定到其自己的 XAML 中,可以声明一个 Style:
<controls:BaseUserControl
x:Class="CompanyNamespace.Controls.GoogleMap"
xmlns:local="clr-namespace:CompanyNamespace.Controls"
...>
<controls:BaseUserControl.Style>
<Style>
<Setter Property="local:GoogleMap.MapCenter" Value="{Binding Location}" />
</Style>
</controls:BaseUserControl.Style>
...
</controls:BaseUserControl>
XML 命名空间local
当然是多余的,如果它与 controls
相同。
您也可以在用户控件的构造函数中创建绑定,如下所示:
public GoogleMap()
{
InitializeComponent();
SetBinding(MapCenterProperty, new Binding("Location"));
}