Xaml on可见性已更改执行某些操作

ego6inou  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(132)

I have element with visibility but I don't know to do something on isVisibleChanged right way.
So lets say I have element with name SomePanel
So I can access SomePanel.IsVisibleChanged
What I found on the internet is

public event DependencyPropertyChangedEventHandler IsSomePanelVisible;
somePanel.IsVisibleChanged += IsSomePanelVisible;

But I need method after += where can I put my logic. How can I do that?

bihw5rsg

bihw5rsg1#

First you have to create the method that will be called :

private void VisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
    {

    }

Then add the handler :

somePanel.IsVisibleChanged += VisibleChanged;

The method can be later in the code, it doesn't matter.
EDIT :
Like Shemberle said, you can also do it from the XAML like this : (expecting that you keep "VisibleChanged" as your method name)

<Panel IsVisibleChanged="VisibleChanged" />

The interesting point to note is that adding it in the XAML creates the "link" between the event and the method from the beginning whereas adding it programatically only creates the link at the moment of your choice. Conversely, you can remove the link in the same way, just change + by - :

somePanel.IsVisibleChanged -= VisibleChanged;
cxfofazt

cxfofazt2#

伊娃的答案是完全正确的。您还可以在xaml代码中添加IsVisibleChanged。例如:在.xaml中

<Label x:Name="label1" Content="Label" IsVisibleChanged="Label_IsVisibleChanged" />

在xaml.cs中

private void Label_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
       //do stuff
    }

相关问题