初始化时未设置WPF依赖项属性

时间:2018-09-17 12:51:10

标签: c# wpf mvvm user-controls dependency-properties

我正在尝试在ViewModel初始化时设置UserControl的宽度,但是它只能接收零。当我调整窗口大小时,它会收到正确的宽度。

MainWindow.xaml提取:

<local:MapControl x:Name="MapControl" 
    DataContext="{Binding MapViewModel}"
    ActualControlWidth="{Binding ActualControlWidth, Mode=OneWayToSource}" />

MapControl.xaml.cs:

public partial class MapControl : UserControl
{
    public MapControl()
    {
        InitializeComponent();
        SizeChanged += OnControlSizeChanged;
    }


    public static readonly DependencyProperty ActualControlWidthProperty = DependencyProperty.Register(
        "ActualControlWidth",
        typeof(double),
        typeof(MapControl),
        new FrameworkPropertyMetadata(PropertyChangedCallback)); //here it does not have any influence if i put default(double) or not

    private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var newVar = e.NewValue;
    }

    public double ActualControlWidth
    {
        get { return (double)GetValue(ActualControlWidthProperty); }
        set { SetValue(ActualControlWidthProperty, value); } //here comes the value as 785
    }

    private void OnControlSizeChanged(object sender, SizeChangedEventArgs e)
    {
        ActualControlWidth = ActualWidth;
    }
}

MapViewModel.cs:

public class MapViewModel : ViewModelBase
{
    private double _actualControlWidth;
    private Map _map;

    public MapViewModel()
    {
       ...
    }

    public Map Map
    {
        get => _map;
        set => Set(() => Map, ref _map, value);
    }

    public double ActualControlWidth
    {
        get => _actualControlWidth;
        set => _actualControlWidth = value; //this is where the value comes as 0
    }
}

感谢您的帮助!

完整的复制示例在我的Github https://github.com/czechdude/dependencypropertyissue

0 个答案:

没有答案