Home > Mobile >  WPF Data binding from ChangedEvent arguments in C#
WPF Data binding from ChangedEvent arguments in C#

Time:08-24

I'm using c# and wpf.

I have an problem with DataBinding. I have a referance to a bluetooth communication dll and when connection done there is DataChanged event returns like DataChangedEventArgs arg. I'm simple version of handling it with

private async void BtOnValueChanged(object sender, DataChangedEventArgs arg)
{
     await this.Dispatcher.InvokeAsync(() =>
           {
                    textblock1.Text=arg.data1;
                    textblock.Text=arg.data2;
                    image1.Visibility=(arg.data3 ? Visibility.Visible : Visibility.Hidden);
                    if(data2>100)
                         textblock1.Foreground=Color.Red;
           });
}

DataChangedEventArgs has a class like

public class DataChangedEventArgs
{
  public string data1 {get;set;}
  public double data2 {get;set;}
  public bool data3 {get;set;}
}

but I want to do it with Xaml Binding. Only a few things that I need to do with event handler. I tried to get it from direct binding Datachangedevent nothing was show up. Also tried to get all args like

public static DataChangedEventArgs DataArg; 
....
....
private async void BtOnValueChanged(object sender, DataChangedEventArgs arg)
{
     await this.Dispatcher.InvokeAsync(() =>
           {
               DataArg=arg;
           });
}

also tried to bind source in code but I couldn't handle it.

Can anyone help me.

CodePudding user response:

Use a property instead of a static variable and a custom data type that implements INotifyPropertyChanged

public class MyBluetoothViewData : INotifyPropertyChanged
{
    private string _data1;
    private double _data2;
    private bool _data3;

    public event PropertyChangedEventHandler PropertyChanged;

    public string data1 { get => _data1; set { _data1 = value; OnPropertyChanged("data1"); } }
    public double data2 { get => _data2; set { _data2 = value; OnPropertyChanged("data2"); } }
    public bool   data3 { get => _data3; set { _data3 = value; OnPropertyChanged("data3"); } }

    protected void OnPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}
public MyBluetoothViewData DataArg { get; set; } = new();

In your event handler:

this.DataArg.data1 = arg.data1;
this.DataArg.data2 = arg.data2;
this.DataArg.data3 = arg.data3;

Then you can bind to it in the XAML

  • Related