gpt4 book ai didi

c# - 将事件从自定义控件传播到窗体

转载 作者:行者123 更新时间:2023-11-30 14:58:49 25 4
gpt4 key购买 nike

我有一个自定义控件,例如:

public sealed class BorderEx : Control
{
public static readonly RoutedEvent ReloadClickEvent = EventManager.RegisterRoutedEvent("ReloadClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(BorderEx));

public event RoutedEventHandler ReloadClick
{
add { AddHandler(ReloadClickEvent, value); }
remove { RemoveHandler(ReloadClickEvent, value); }
}

void RaiseReloadClickEvent()
{
var newEventArgs = new RoutedEventArgs(ReloadClickEvent);
RaiseEvent(newEventArgs);
}

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

并且在 reloadButton 单击 generic.xaml 时会引发事件

<ControlTemplate TargetType="{x:Type cbr:BorderEx}">

<ControlTemplate.Triggers>

<Trigger SourceName="reloadButton" Property="IsPressed" Value="True">
<Setter TargetName="reloadButton" Property="Background" Value="Green"/>
<EventSetter Event="ReloadClick" Handler="RaiseReloadClickEvent"></EventSetter>
</Trigger>
</ControlTemplate.Triggers>

</ControlTemplate

但我不知道如何从内部按钮引发此外部事件。花了最后几个小时谷歌搜索,结果一无所获。以上 EventSetter 不工作。

最佳答案

这部分没问题,

    public static readonly RoutedEvent ReloadClickEvent = EventManager.RegisterRoutedEvent("ReloadClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(BorderEx));

public event RoutedEventHandler ReloadClick
{
add { AddHandler(ReloadClickEvent, value); }
remove { RemoveHandler(ReloadClickEvent, value); }
}

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

我必须创建依赖属性,所以我可以更改一些点击事件的值

    public static readonly DependencyProperty ReloadProperty = DependencyProperty.Register("Reload", typeof (bool), typeof (BorderEx), new PropertyMetadata(default(bool), ReloadClicked));
public bool Reload
{
get { return (bool) GetValue(ReloadProperty); }
set { SetValue(ReloadProperty, value); }
}

而且我可以在更改时触发的其他方法中处理它

    private static void ReloadClicked(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
if (!((bool) e.NewValue)) return;
var sender = (BorderEx) o;
sender.RaiseEvent(new RoutedEventArgs(ReloadClickEvent));
}

然后它只需要改变点击的值(value)

<ControlTemplate.Triggers>
<Trigger SourceName="reloadButton" Property="IsPressed" Value="True">
<Setter TargetName="reloadButton" Property="Background" Value="Green"/>
<Setter Property="Reload" Value="True"/>
</Trigger>
</ControlTemplate.Triggers>

关于c# - 将事件从自定义控件传播到窗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17975556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com