2017-03-26 54 views
0

我很努力地將代碼中的綁定隱藏到靜態屬性中。 在WPF從來就做到了,如下圖所示:在代碼背後綁定靜態屬性

<TextBlock Text="{Binding Source={x:Static local:LogListener.Instance}, Path=LogItem.LogType}" Margin="2" /> 

現在我要綁定「LogItem」針對新的DP

#region LogItem 

    public static readonly DependencyProperty LogItemProperty = DependencyProperty.Register(
     "LogItem", typeof(LogItem), typeof(NpLoggerControl), 
     new PropertyMetadata(default(LogItem), LogItemPropertyChanged)); 

    private static void LogItemPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) 
    { 
     var type = source as NpLoggerControl; 
     type?.LogItemPropertyChanged(e); 
    } 

    protected virtual void LogItemPropertyChanged(DependencyPropertyChangedEventArgs e) 
    { 
     var item = (LogItem) e.NewValue; 
    } 

    public LogItem LogItem 
    { 
     get { return (LogItem) GetValue(LogItemProperty); } 
     set { SetValue(LogItemProperty, value); } 
    } 

從來就沒有知道如何設置它的代碼

+0

沒有設置綁定programmaticall點在這種情況下。您可以將依賴項屬性設置爲靜態LogType屬性的值。 – mm8

回答

1

您可以設置,就像你在XAML做的屬性:

textBlock.SetBinding(
    TextBlock.TextProperty, 
    new Binding 
    { 
     Source = LogListener.Instance, 
     Path = new PropertyPath("LogItem.LogType") 
    });