oronsultan Ответов: 1

Подписался на dependencypropertychangedevent


Hey gusy,
In wpf & C#, i have a user control (name: "Package_Combo") and inside it i have a label. 
the label content getting its value from DependencyProperty called LabelContentProperty.
the LabelContentProperty is register to a string property called LabelContent: 

public static readonly DependencyProperty LabelContentProperty = DependencyProperty.Register(LabelContent, typeof(string), 
typeof(Package_Combo), new PropertyMetadata(null, new PropertyChangedCallback(LabelContentChanged)));

public string LabelContent
{
    get { return (string)GetValue(LabelContentProperty); }
    set { SetValue(LabelContentProperty, value); }
}

public string LabelContent
{
     get { return (string)GetValue(LabelContentProperty); }
     set { SetValue(LabelContentProperty, value);}
}

private static void LabelContentChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
{
	//code goes here...
}

In xaml, the label content set like that:
 <Label x:Name="lbl" Content="{Binding ElementName=PackageCombo, Path=LabelContent}"/>

Now here is the problem:
Whenever the content is changes, its fire the LabelContentChanged event.
In that event, i want to fire a non-static function ("GetComboDataSource") that initial the itemsource of a combobox that also is in the same user control.
I cant set "GetComboDataSource" to static beacuse the function uses a dispather to handle web-api result. this is the logic:

public DataTable GetComboDataSource()
        {
            try
            {
                HttpClient client = new HttpClient();
                HttpRequestMessage request;

                string controller, function;
                string[] s = ControllerAndFunc.Split('-');
                controller = s[0];function = s[1];
                string serviceUrl = GV.ServiceUrl + controller + @"/" + function;

                var paramsList = new List<ParamsList>();
                paramsList.Add(new ParamsList { ParamName = ParameterConsts.language, ParamValue = Utils.GetLanguageId().ToString() });

                serviceUrl = Utils.ServiceUrlBuilder(paramsList, serviceUrl);
                request = new HttpRequestMessage(HttpMethod.Get, serviceUrl);
                Task<HttpResponseMessage> responseTask = client.SendAsync(request);

                DataTable result = null;
                string displayMember = DisplayMemberPath;
                string selectedValue = SelectedValuePath;
                Task continuation = responseTask.ContinueWith(x => result = HandleResult(x, paramsList, displayMember, selectedValue));
                Task.WaitAll();
                return result;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
        private DataTable HandleResult(Task<HttpResponseMessage> httpTask, List<ParamsList> userParamsList, string displayMember, string selectedValue)
        {
            try
            {
                Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
                string result = string.Empty;
                Task continuation = task.ContinueWith(t =>
                {
                    result = t.Result;
                    Data = (DataTable)JsonConvert.DeserializeObject(result, (typeof(DataTable)));
                    Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(() =>
                    {
                        this.DataContext = this;
                        cmb.DisplayMemberPath = displayMember;
                        cmb.SelectedValue = selectedValue;
                    }));
                });
                Task.WaitAll();
                return Data;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

How can i call GetComboDataSource within LabelContentChanged without creating object reference?


Что я уже пробовал:

i have tried working with delegates and dispatcher but without any luck

1 Ответов

Рейтинг:
10

Richard Deeming

То DependencyObject параметр, переданный в LabelContentChanged обработчик событий будет экземпляром вашего элемента управления, для которого свойство изменилось. Вам просто нужно привести его к соответствующему типу и вызвать свой метод:

private static void LabelContentChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
{
    YourControl theControl = (YourControl)dependencyObject;
    theControl.OnLabelContentChanged(eventArgs);
}

private void OnLabelContentChanged(DependencyPropertyChangedEventArgs eventArgs)
{
    ...
}


oronsultan

Отличное решение, Ричард, большое спасибо!