Question

I am new to WPF and C# im trying to understand how can I update a UI element from a BL class (to keep a seperation between the logic and the UI) the bl gets periodic updates from a c++ network component and should update the form once a new argument comes in (I read on the msdn website but I want to see some concrete examples to make sure I got it right)

Was it helpful?

Solution

Because of your gets periodic updates from a c++ network component comment, I am assuming that you already have a system to update your property. I would expose that property from your business class in a view model class, a class with public properties and ICommand functions designed specifically to supply all of the required data to a view, or UserControl.

To be honest, I wouldn't have that (or any) functionality in a business class (depending what you mean by business class)... I'd personally put it straight into the view model, or have a manager/service class that exposed it.

If you insist on keeping it where it is, you'll have to implement either an event or a delegate in your business class so that users of that class can be alerted as to when the value changes. Then you could simply attach a handler to your event/delegate from the view model class and easily update the exposed property whenever the actual property changes.

So it would go a little something like this... in your business class (I am assuming that your value is an int, but you can change this if it is incorrect... the principal is the same):

public delegate void FieldUpdate(int value);

public FieldUpdate OnFieldUpdate { get; set; }

...

private int field;

public int Field
{
    get { return field; }
    set
    {
        if (value != field)
        {
            field = value;
            if (OnFieldUpdate != null) OnFieldUpdate(field);
        }
    }
}

Then in your view model:

private YourBusinessClass instance = new YourBusinessClass();

public YourBusinessClass Instance 
{
    get { return instance; }
    set { instance = value; NotifyPropertyChanged("Instance"); }
}

Attach a handler:

instance.OnFieldUpdate += OnBusinessClassFieldUpdate;

...

public void OnBusinessClassFieldUpdate(int value)
{
    Instance = value;
}

Now whenever the field is updated in the business class, the view model (and data bound UI controls) will automatically update via the delegate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top