Data binding 将依赖项属性绑定为目标不';行不通
我创建的依赖项属性如下所示:Data binding 将依赖项属性绑定为目标不';行不通,data-binding,dependency-properties,Data Binding,Dependency Properties,我创建的依赖项属性如下所示: public class MapShowViewModel : DependencyObject { public static readonly DependencyProperty MapScaleProperty = DependencyProperty.Register("MapScale", typeof(double), typeof(MapShowViewModel), new Framework
public class MapShowViewModel : DependencyObject
{
public static readonly DependencyProperty MapScaleProperty =
DependencyProperty.Register("MapScale",
typeof(double), typeof(MapShowViewModel),
new FrameworkPropertyMetadata(Convert.ToDouble(1), OnMapScaleChanged));
private static void OnMapScaleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var mapShowViewModel = d as MapShowViewModel;
if (mapShowViewModel == null) return;
mapShowViewModel.MapScale = Convert.ToDouble(e.NewValue);
}
public double MapScale
{
get { return (double)GetValue(MapScaleProperty); }
set { SetValue(MapScaleProperty, value); }
}
}
<baseVm:MapShowViewModel x:Key="MapShowViewModel"
MapScale="{Binding ElementName=MyMap, Path=Scale,
UpdateSourceTrigger=PropertyChanged,
Mode=TwoWay, Converter={StaticResource MapScaleConverter}}" />
当在Resource中定义ViewModel时,我将XAML中的dp绑定到名为“MyMap”的元素,并有一个名为“Scale”的双类型属性,如下所示:
public class MapShowViewModel : DependencyObject
{
public static readonly DependencyProperty MapScaleProperty =
DependencyProperty.Register("MapScale",
typeof(double), typeof(MapShowViewModel),
new FrameworkPropertyMetadata(Convert.ToDouble(1), OnMapScaleChanged));
private static void OnMapScaleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var mapShowViewModel = d as MapShowViewModel;
if (mapShowViewModel == null) return;
mapShowViewModel.MapScale = Convert.ToDouble(e.NewValue);
}
public double MapScale
{
get { return (double)GetValue(MapScaleProperty); }
set { SetValue(MapScaleProperty, value); }
}
}
<baseVm:MapShowViewModel x:Key="MapShowViewModel"
MapScale="{Binding ElementName=MyMap, Path=Scale,
UpdateSourceTrigger=PropertyChanged,
Mode=TwoWay, Converter={StaticResource MapScaleConverter}}" />
但MapScale属性的值不会随地图元素的比例属性的更改而更改