programing

종속 속성에서 속성 변경 이벤트를 발생시키는 방법

stoneblock 2023. 4. 14. 21:07

종속 속성에서 속성 변경 이벤트를 발생시키는 방법

나는 두 가지 속성을 가진 통제권을 가지고 있다.는 ★★★★★★★★★★★★★★★.DependencyProperty 다른 는 첫 와 '자'입니다. '오빠'를 올릴 수 요?PropertyChanged첫 번째 이벤트(에일리어스)가 변경되었을 때 두 번째 이벤트(에일리어스)에 대한 이벤트입니다.

메모: 사용 중DependencyObjects 아니라, 이에요.INotifyPropertyChanged, 내 이 a이기 하지 않았습니다.)ListVie★★★★★★★★★★★★★★★★★★)

이런 거...

protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
    base.OnPropertyChanged(e);
    if (e.Property == MyFirstProperty)
    {
        RaiseAnEvent( MySecondProperty ); /// what is the code that would go here?
    }    
}

Inotify를 사용하면 이렇게 할 수 있는데...

public string SecondProperty
{
    get
    {
        return this.m_IconPath;
    }
}

public string IconPath
{
    get
    {
        return this.m_IconPath;
    }
    set
    {
        if (this.m_IconPath != value)
        {
            this.m_IconPath = value;
        this.SendPropertyChanged("IconPath");
        this.SendPropertyChanged("SecondProperty");
        }
    }
}

서 키워야 하나요?PropertyChanged하나의 세터에서 여러 개의 속성에서 이벤트를 발생시킬 수 있습니까? 수 단, 사용방법만 해야 합니다.DependencyProperties.

클래스가 변경 이벤트를 듣고 서비스에서 관련 데이터를 가져오도록 하는 종속성 속성이 있는 것과 유사한 문제가 발생했습니다.

public static readonly DependencyProperty CustomerProperty = 
    DependencyProperty.Register("Customer", typeof(Customer),
        typeof(CustomerDetailView),
        new PropertyMetadata(OnCustomerChangedCallBack));

public Customer Customer {
    get { return (Customer)GetValue(CustomerProperty); }
    set { SetValue(CustomerProperty, value); }
}

private static void OnCustomerChangedCallBack(
        DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    CustomerDetailView c = sender as CustomerDetailView;
    if (c != null) {
        c.OnCustomerChanged();
    }
}

protected virtual void OnCustomerChanged() {
    // Grab related data.
    // Raises INotifyPropertyChanged.PropertyChanged
    OnPropertyChanged("Customer");
}
  1. INotifyPropertyChanged네 반에서.

  2. 종속성 속성을 등록할 때 속성 메타데이터에 콜백을 지정합니다.

  3. ""를 .PropertyChanged

콜백 추가:

public static DependencyProperty FirstProperty = DependencyProperty.Register(
  "First", 
  typeof(string), 
  typeof(MyType),
  new FrameworkPropertyMetadata(
     false, 
     new PropertyChangedCallback(OnFirstPropertyChanged)));

PropertyChanged★★★★

private static void OnFirstPropertyChanged(
   DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
   PropertyChangedEventHandler h = PropertyChanged;
   if (h != null)
   {
      h(sender, new PropertyChangedEventArgs("Second"));
   }
}

작전본부가 잘못된 질문을 하는 것 같아요.는 수동으로 .PropertyChanged'이벤트'은 '이렇게'를 다루는 입니다.PropertyChanged종속성 속성에 대한 CALLBACK 및 다른 종속성 속성에 대한 값을 설정합니다.다음은 작업 예입니다.에는 '''가 있습니다.MyControl에는 두 이 있습니다.ActiveTabInt ★★★★★★★★★★★★★★★★★」ActiveTabString의 버튼( 「 )을 MainWindowActiveTabString변경되어 있습니다.PropertyChanged은 "CALLBACK"의 합니다.ActiveTabInt . 。PropertyChanged는 EVENT에 의해 .MyControl.

MainWindow.xaml.cs

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        ActiveTabString = "zero";
    }

    private string _ActiveTabString;
    public string ActiveTabString
    {
        get { return _ActiveTabString; }
        set
        {
            if (_ActiveTabString != value)
            {
                _ActiveTabString = value;
                RaisePropertyChanged("ActiveTabString");
            }
        }
    }

    private int _ActiveTabInt;
    public int ActiveTabInt
    {
        get { return _ActiveTabInt; }
        set
        {
            if (_ActiveTabInt != value)
            {
                _ActiveTabInt = value;
                RaisePropertyChanged("ActiveTabInt");
            }
        }
    }

    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ActiveTabString = (ActiveTabString == "zero") ? "one" : "zero";
    }

}

public class MyControl : Control
{
    public static List<string> Indexmap = new List<string>(new string[] { "zero", "one" });


    public string ActiveTabString
    {
        get { return (string)GetValue(ActiveTabStringProperty); }
        set { SetValue(ActiveTabStringProperty, value); }
    }

    public static readonly DependencyProperty ActiveTabStringProperty = DependencyProperty.Register(
        "ActiveTabString",
        typeof(string),
        typeof(MyControl), new FrameworkPropertyMetadata(
            null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            ActiveTabStringChanged));


    public int ActiveTabInt
    {
        get { return (int)GetValue(ActiveTabIntProperty); }
        set { SetValue(ActiveTabIntProperty, value); }
    }
    public static readonly DependencyProperty ActiveTabIntProperty = DependencyProperty.Register(
        "ActiveTabInt",
        typeof(Int32),
        typeof(MyControl), new FrameworkPropertyMetadata(
            new Int32(),
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));


    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));

    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }


    private static void ActiveTabStringChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MyControl thiscontrol = sender as MyControl;

        if (Indexmap[thiscontrol.ActiveTabInt] != thiscontrol.ActiveTabString)
            thiscontrol.ActiveTabInt = Indexmap.IndexOf(e.NewValue.ToString());

    }
}

Main Window.xaml

    <StackPanel Orientation="Vertical">
    <Button Content="Change Tab Index" Click="Button_Click" Width="110" Height="30"></Button>
    <local:MyControl x:Name="myControl" ActiveTabInt="{Binding ActiveTabInt, Mode=TwoWay}" ActiveTabString="{Binding ActiveTabString}"></local:MyControl>
</StackPanel>

App.xaml

<Style TargetType="local:MyControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:MyControl">
                    <TabControl SelectedIndex="{Binding ActiveTabInt, Mode=TwoWay}">
                        <TabItem Header="Tab Zero">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                        <TabItem Header="Tab One">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                    </TabControl>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

나는 Sam과 Xaser의 의견에 동의하고 실제로 이것을 좀 더 진전시켰다.안것 요.INotifyPropertyChangedUserControl컨트롤은 이미 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」DependencyObject이치노" " " INotifyPropertyChanged a까지DependencyObject이렇게 해서 '우리'는 '우리'는요.

가 한 것은 두 proper지가 both both what 、 두 、 what 、 what 、 what 、 what 、 what 、 what 、 what 。DependencyProperties이 제안하는 '그냥' '그냥' '그냥' '그냥' '그냥' '그냥' '그냥' '그냥' '그냥' '그냥' '그냥' '그냥' '그냥' '그냥'이 있었어'PropertyChangedCallback"첫 번째" 종속 속성에서 "두 번째" 종속 속성 값을 변경합니다.둘 다 의존관계 속성이기 때문에 둘 다 관심 있는 가입자에게 변경 알림을 자동으로 보냅니다(데이터 바인딩 등).

이 경우 종속성 속성 A는 문자열입니다.InviteText이것에 의해, 의존 속성 B 의 변경이 트리거 됩니다.Visibility명명된 속성ShowInvite이것은 데이터 바인딩을 통해 컨트롤에서 완전히 숨길 수 있는 텍스트가 있는 경우 일반적인 사용 사례입니다.

public string InviteText  
{
    get { return (string)GetValue(InviteTextProperty); }
    set { SetValue(InviteTextProperty, value); }
}

public static readonly DependencyProperty InviteTextProperty =
    DependencyProperty.Register("InviteText", typeof(string), typeof(InvitePrompt), new UIPropertyMetadata(String.Empty, OnInviteTextChanged));

private static void OnInviteTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    InvitePrompt prompt = d as InvitePrompt;
    if (prompt != null)
    {
        string text = e.NewValue as String;
        prompt.ShowInvite = String.IsNullOrWhiteSpace(text) ? Visibility.Collapsed : Visibility.Visible;
    }
}

public Visibility ShowInvite
{
    get { return (Visibility)GetValue(ShowInviteProperty); }
    set { SetValue(ShowInviteProperty, value); }
}

public static readonly DependencyProperty ShowInviteProperty =
    DependencyProperty.Register("ShowInvite", typeof(Visibility), typeof(InvitePrompt), new PropertyMetadata(Visibility.Collapsed));

주의: 이 명령어에는 포함되지 않습니다.UserControl시그니처 또는 컨스트럭터에는 특별한 것이 없기 때문에 여기서의 시그니처 또는 컨스트럭터는 서브클래스를 할 필요가 없습니다.INotifyPropertyChanged조금도.

이 문제를 제기하는 논리에 의문을 제기합니다.PropertyChanged첫 번째 속성이 변경되었을 때 두 번째 속성이 이벤트를 발생시킵니다.두 번째 속성 값이 변경되면PropertyChanged이벤트가 발생할 수 있습니다.

어쨌든, 당신의 질문에 대한 답변은 다음과 같습니다.INotifyPropertyChange이 인터페이스에는,PropertyChanged이벤트. 구현INotifyPropertyChanged다른 코드에 클래스가 있는 것을 통지합니다.PropertyChanged이 코드를 사용하여 핸들러를 연결할 수 있습니다.구현 후INotifyPropertyChangeif 스테이트먼트에 들어가는 코드OnPropertyChanged다음과 같습니다.

if (PropertyChanged != null)
    PropertyChanged(new PropertyChangedEventArgs("MySecondProperty"));

이전에 받아들인 답변에 기초하여, 출연자들이 비정적 영화에 접근할 수 없었다.PropertyChanged:

  1. 시행하다INotifyPropertyChanged예를 들어, 당신의 수업에서.UserControl CustomView

  2. 종속성 속성을 등록할 때 속성 메타데이터에 콜백을 지정합니다.

  3. 콜백에서 캐스트하고 올립니다.PropertyChanged이벤트입니다.

콜백 추가:

public static DependencyProperty FirstProperty = DependencyProperty.Register(
  "First", 
  typeof(string), 
  typeof(MyType),
  new FrameworkPropertyMetadata(
     false, 
     new PropertyChangedCallback(OnFirstPropertyChanged)));

발신자를 캐스팅하고 콜백에서 Property Changed를 올립니다.

private static void OnFirstPropertyChanged(
   DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
   var control = (CustomView)sender;
   PropertyChangedEventHandler h = control.PropertyChanged;
   if (h != null)
   {
      h(sender, new PropertyChangedEventArgs("Second"));
   }
}

언급URL : https://stackoverflow.com/questions/2480366/how-to-raise-property-changed-events-on-a-dependency-property