我的控件中有一个依赖项属性,该属性将OneWayToSource绑定到视图模型。我不知道如何用一个非静态值初始化它。如果我尝试在控件的构造函数中对其进行初始化,则属性值将更改为所需的值,但是由于某种原因会立即将其更改回原值。考虑以下代码:
ButterflyControl.xaml.cs
using System;
using System.Diagnostics;
using System.Windows;
namespace OneWayToSourceTest
{
public partial class ButterflyControl
{
public ButterflyControl()
{
InitializeComponent();
RefreshAction = Refresh;
}
public static readonly DependencyProperty RefreshActionProperty = DependencyProperty.Register(
name: nameof(RefreshAction),
propertyType: typeof(Action),
ownerType: typeof(ButterflyControl),
typeMetadata: new PropertyMetadata(null, RefreshActionPropertyChanged));
public Action RefreshAction
{
get => (Action)GetValue(RefreshActionProperty);
set => SetValue(RefreshActionProperty, value);
}
private static void RefreshActionPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
// For debugging purposes, observe changed to the RefreshAction property.
Debug.WriteLine("RefreshAction changed from '{0}' to '{1}'", (e.OldValue as Action)?.Method.Name, (e.NewValue as Action)?.Method.Name);
}
private void Refresh()
{
// Refresh code goes here.
}
}
}
ButterflyControl.xaml
<UserControl x:Class="OneWayToSourceTest.ButterflyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800" >
<Grid />
</UserControl>
MainWindow.xaml
<Window x:Class="OneWayToSourceTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:oneWayToSourceTest="clr-namespace:OneWayToSourceTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<oneWayToSourceTest:ButterflyControl RefreshAction="{Binding RefreshAction, Mode=OneWayToSource}" />
</Window>
Startup.cs
using System;
namespace OneWayToSourceTest
{
public static class Startup
{
[STAThread]
public static void Main()
{
MainWindow window = new MainWindow();
}
}
}
运行该程序时,输出窗口显示:
RefreshAction从''更改为``Refresh''
RefreshAction从``Refresh''更改为``
我在某个地方犯了一个错误,还是我采取了错误的方法?如果我采用了错误的方法,用非静态值初始化OneWayToSource依赖项属性的合适方法是什么?
答案 0 :(得分:1)
将初始化移至Loaded事件处理程序,该事件处理程序在建立绑定之后调用。
public ButterflyControl()
{
InitializeComponent();
Loaded += (s, e) => RefreshAction = Refresh;
}
有关更多信息,请参见Object Lifetime Events。