绑定到

时间:2017-03-26 20:00:25

标签: c# wpf binding

我很难在代码中获得静态属性的绑定。 在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); }
    }

我不知道如何在Code

中进行设置

1 个答案:

答案 0 :(得分:2)

您可以像在XAML中一样设置属性:

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