0
依存関係プロパティを使用してユーザーコントロールを作成しようとしています。依存関係プロパティがusercontrolの外から変更されたときに特定のロジックを実行する必要がありますが、依存関係プロパティがユーザーコントロールの内部から変更されたときにそのロジックを実行すべきではありません。私はこの小さなサンプルを持っています。私は、値がメインウィンドウから設定されている場合にのみ特定のロジックを実行し、チェックボックスをクリックして設定されている場合は実行しません。 PropertyChangedCallback
が正しい方法であるかどうかわかりませんが、これは私が持っているものです。片方向依存プロパティが通知を変更しました
ユーザーコントロール:
public partial class UserControl1 : UserControl
{
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int), typeof(UserControl1), new PropertyMetadata(new PropertyChangedCallback(OnPropertyChanged)));
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Only process the 5, don't process the 6
}
public UserControl1()
{
InitializeComponent();
}
private void checkBox_Click(object sender, RoutedEventArgs e)
{
MyProperty = 6;
}
}
ユーザーコントロールのXAML:
<UserControl x:Class="WpfApplication4.UserControl1"
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="300" d:DesignWidth="300">
<Grid>
<CheckBox x:Name="checkBox" Click="checkBox_Click"/>
</Grid>
</UserControl>
メインウィンドウ:
public partial class MainWindow : Window
{
public int MainWindowProperty { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
MainWindowProperty = 5;
}
}
メインウィンドウXAML:
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:UserControl1 MyProperty="{Binding MainWindowProperty}"/>
</Grid>
</Window>
本当に、それは簡単ですか?私はとても馬鹿だと感じる。これを答えにする前に、実際のアプリケーションでそれを試してみましょう。 –