在事件内订阅事件

问题描述 投票:-1回答:1
Control.LostFocus += Control_LostFocus;

private void Control_LostFocus(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
     Control.TextChanged += Control_TextChanged;
}

private void Control_TextChanged (object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
     MessagingCenter.Send<object>(this, Messaging.Edited);
}

这就是我们绑定的方式,因此每次打开页面时它都会更新值,该值也会触发TextChanged

public string Binding
{
    get { return _binding; }
    set { Set(ref _binding, value); }
}

它应用于自定义渲染器,因为我需要一次验证多个Entry。

我订阅了这些事件以验证在编辑模式期间Entry值是否已更改。但是条目使用绑定,因此它检测到值已经改变,这就是我首先使用LostFocus的原因。

如何在活动中订阅活动?

我是编程的新手,我的同事告诉我重构它,因为它可能会导致性能问题。

解决方法是什么?

谢谢你的回答。

c# events xamarin
1个回答
0
投票

我不熟悉WPF。但是,如果您在代码中设置绑定和订阅事件,则可以尝试在绑定代码之后订阅事件。例如:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        MyDataSource ds = new MyDataSource { Name = "Hello World" };
        Binding b = new Binding("Name");
        b.Source = ds;
        tb.SetBinding(TextBox.TextProperty, b); // tb is of type TextBox
        tb.TextChanged += Tb_TextChanged; // subscribe event after binding
    }

    private void Tb_TextChanged(object sender, TextChangedEventArgs e)
    {
        lbl.Content = tb.Text; // lbl is of type Label
    }
}

public class MyDataSource
{
    public string Name { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.