如上图,我有一个自定义控件Map,它拥有四个用于控制地图缩放的依赖属性,允许用户App.Config来修改默认值, 所以在程序里用Settings.settings设定。


WPF绑定到Properties.Settings的几种方法_ide


如上图,我有一个自定义控件Map,它拥有四个用于控制地图缩放的依赖属性,允许用户App.Config来修改默认值,

所以在程序里用Settings.settings设定。

1.C#代码方式



Binding binding = new Binding("MapZoom");

binding.Source = Properties.Settings.Default;

map.SetBinding(Map.ZoomProperty, binding);

binding = new Binding("MapZoomMax");

binding.Source = Properties.Settings.Default;

map.SetBinding(Map.ZoomMaxProperty, binding);

binding = new Binding("MapZoomMin");

binding.Source = Properties.Settings.Default;

map.SetBinding(Map.ZoomMinProperty, binding);

binding = new Binding("MapZoomSpan");

binding.Source = Properties.Settings.Default;

map.SetBinding(Map.ZoomSpanProperty, binding);


 

2.XAML方式(推荐)

xmlns:Properties="clr-namespace:Application1.Properties"


<Views:Map DockPanel.Dock="Top" 

 Zoom="{Binding Path=MapZoom,Source={x:Static Properties:Settings.Default}}" 

 ZoomMax="{Binding Path=MapZoomMax,Source={x:Static Properties:Settings.Default}}" 

 ZoomMin="{Binding Path=MapZoomMin,Source={x:Static Properties:Settings.Default}}" 

 ZoomSpan="{Binding Path=MapZoomSpan,Source={x:Static Properties:Settings.Default}}" />


3.XAML方式,通过ObjectDataProvider

xmlns:local="clr-namespace:Application1"


<ObjectDataProvider x:Key="OdpSettings" ObjectType="{x:Type local:Properties.Settings}"></ObjectDataProvider>


<Views:Map DockPanel.Dock="Top" 

 Zoom="{Binding Path=Default.MapZoom,Source={StaticResource OdpSettings}}" 

 ZoomMax="{Binding Path=Default.MapZoomMax,Source={StaticResource OdpSettings}}" 

 ZoomMin="{Binding Path=Default.MapZoomMin,Source={StaticResource OdpSettings}}" 

 ZoomSpan="{Binding Path=Default.MapZoomSpan,Source={StaticResource OdpSettings}}" />