簡體   English   中英

XAML中的動態內容

[英]Dynamic content in xaml

如果要基於條件顯示某些內容,則簡單的方法是使用可見性綁定:

<Something Visibility="{Binding ShowSomething, Converter=..." ... />

通過這種方法,如果Something具有復雜的結構(許多子級,綁定,事件,觸發器等),則仍會創建可視化樹並可能導致性能問題。


更好的方法是通過觸發器添加內容:

<ContentControl>
    <ContentControl.Style>
        <Style TargetType="ContentControl">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ShowSomething}" Value="SomeValue">
                    <Setter Property="Content">
                        <Setter.Value>
                            <Something ... />
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ContentControl.Style>
</ContentControl>

但這是一場噩夢,同意嗎? 具有多個這樣的動態部分將污染xaml並使其難以導航。

還有另一種方法嗎?


我會盡可能使用數據模板,但是當動態部分僅取決於屬性值時,創建專用Type並實際定義數據模板實在太多了。 當然,可以將該屬性重構為一個類型,然后可以使用其自己的數據模板,但是可以。 我真的更喜歡每次都不要這樣做,因為xaml中定義的太多小類型和實際數據模板對我來說聽起來都是不好的。

我實際上喜歡第二種方法,但是我想改進它,例如通過進行xaml-extension或自定義控件。 我決定提出問題是因為:1)我很懶;)2)我不確定最好的方法是什么3)我確定其他人(xaml大師)已經解決了這個問題。

我能想到的最可重用的解決方案是創建自定義控件,並將其內容包裝在ControlTemplate ,以便在需要時將其延遲加載。

這是一個示例實現:

[ContentProperty(nameof(Template))]
public class ConditionalContentControl : FrameworkElement
{
    protected override int VisualChildrenCount => Content != null ? 1 : 0;

    protected override Size ArrangeOverride(Size finalSize)
    {
        if (Content != null)
        {
            if (ShowContent)
                Content.Arrange(new Rect(finalSize));
            else
                Content.Arrange(new Rect());
        }
        return finalSize;
    }

    protected override Visual GetVisualChild(int index)
    {
        if (index < 0 || index > VisualChildrenCount - 1)
            throw new ArgumentOutOfRangeException(nameof(index));
        return Content;
    }

    private void LoadContent()
    {
        if (Content == null)
        {
            if (Template != null)
                Content = (UIElement)Template.LoadContent();
            if (Content != null)
            {
                AddLogicalChild(Content);
                AddVisualChild(Content);
            }
        }
    }

    protected override Size MeasureOverride(Size constraint)
    {
        var desiredSize = new Size();
        if (Content != null)
        {
            if (ShowContent)
            {
                Content.Measure(constraint);
                desiredSize = Content.DesiredSize;
            }
            else
                Content.Measure(new Size());
        }
        return desiredSize;
    }

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);
        if (e.Property == ShowContentProperty)
        {
            if (ShowContent)
                LoadContent();
        }
        else if (e.Property == TemplateProperty)
        {
            UnloadContent();
            Content = null;
            if (ShowContent)
                LoadContent();
        }
    }

    private void UnloadContent()
    {
        if (Content != null)
        {
            RemoveVisualChild(Content);
            RemoveLogicalChild(Content);
        }
    }

    #region Dependency properties

    private static readonly DependencyPropertyKey ContentPropertyKey = DependencyProperty.RegisterReadOnly(
        nameof(Content),
        typeof(UIElement),
        typeof(ConditionalContentControl),
        new FrameworkPropertyMetadata
        {
            AffectsArrange = true,
            AffectsMeasure = true,
        });
    public static readonly DependencyProperty ContentProperty = ContentPropertyKey.DependencyProperty;
    public static readonly DependencyProperty ShowContentProperty = DependencyProperty.Register(
        nameof(ShowContent),
        typeof(bool),
        typeof(ConditionalContentControl),
        new FrameworkPropertyMetadata
        {
            AffectsArrange = true,
            AffectsMeasure = true,
            DefaultValue = false,
        });
    public static readonly DependencyProperty TemplateProperty = DependencyProperty.Register(
        nameof(Template),
        typeof(ControlTemplate),
        typeof(ConditionalContentControl),
        new PropertyMetadata(null));

    public UIElement Content
    {
        get => (UIElement)GetValue(ContentProperty);
        private set => SetValue(ContentPropertyKey, value);
    }

    public ControlTemplate Template
    {
        get => (ControlTemplate)GetValue(TemplateProperty);
        set => SetValue(TemplateProperty, value);
    }

    public bool ShowContent
    {
        get => (bool)GetValue(ShowContentProperty);
        set => SetValue(ShowContentProperty, value);
    }

    #endregion
}

請注意,此實現不會在加載內容后立即卸載內容,而只是將其排列為(0,0)大小。 為了在不希望顯示時從視覺樹中卸載內容,我們需要進行一些修改(此代碼示例僅限於修改后的代碼):

(...)

    protected override int VisualChildrenCount => ShowContent && Content != null ? 1 : 0;

    protected override Size ArrangeOverride(Size finalSize)
    {
        if (Content != null && ShowContent)
            Content.Arrange(new Rect(finalSize));
        return finalSize;
    }

    protected override Visual GetVisualChild(int index)
    {
        if (index < 0 || index > VisualChildrenCount - 1)
            throw new ArgumentOutOfRangeException(nameof(index));
        return Content;
    }

    private void LoadContent()
    {
        if (Content == null && Template != null)
            Content = (UIElement)Template.LoadContent();
        if (Content != null)
        {
            AddLogicalChild(Content);
            AddVisualChild(Content);
        }
    }

    protected override Size MeasureOverride(Size constraint)
    {
        var desiredSize = new Size();
        if (Content != null && ShowContent)
        {
            Content.Measure(constraint);
            desiredSize = Content.DesiredSize;
        }
        return desiredSize;
    }

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);
        if (e.Property == ShowContentProperty)
        {
            if (ShowContent)
                LoadContent();
            else
                UnloadContent();
        }
        else if (e.Property == TemplateProperty)
        {
            UnloadContent();
            Content = null;
            if (ShowContent)
                LoadContent();
        }
    }

(...)

用法示例:

<StackPanel>
    <CheckBox x:Name="CB" Content="Show content" />
    <local:ConditionalContentControl ShowContent="{Binding ElementName=CB, Path=IsChecked}">
        <ControlTemplate>
            <Border Background="Red" Height="200" />
        </ControlTemplate>
    </local:ConditionalContentControl>
</StackPanel>

如果您不介意在解析XAML時實例化的內容,而只想將其保留在可視樹之外,則可以使用以下控件來實現此目標:

[ContentProperty(nameof(Content))]
public class ConditionalContentControl : FrameworkElement
{
    private UIElement _Content;
    public UIElement Content
    {
        get => _Content;
        set
        {
            if (ReferenceEquals(value, _Content)) return;
            UnloadContent();
            _Content = value;
            if (ShowContent)
                LoadContent();
        }
    }

    protected override int VisualChildrenCount => ShowContent && Content != null ? 1 : 0;

    protected override Size ArrangeOverride(Size finalSize)
    {
        if (Content != null && ShowContent)
            Content.Arrange(new Rect(finalSize));
        return finalSize;
    }

    protected override Visual GetVisualChild(int index)
    {
        if (index < 0 || index > VisualChildrenCount - 1)
            throw new ArgumentOutOfRangeException(nameof(index));
        return Content;
    }

    private void LoadContent()
    {
        if (Content != null)
        {
            AddLogicalChild(Content);
            AddVisualChild(Content);
        }
    }

    protected override Size MeasureOverride(Size constraint)
    {
        var desiredSize = new Size();
        if (Content != null && ShowContent)
        {
            Content.Measure(constraint);
            desiredSize = Content.DesiredSize;
        }
        return desiredSize;
    }

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);
        if (e.Property == ShowContentProperty)
        {
            if (ShowContent)
                LoadContent();
            else
                UnloadContent();
        }
    }

    private void UnloadContent()
    {
        if (Content != null)
        {
            RemoveVisualChild(Content);
            RemoveLogicalChild(Content);
        }
    }

    #region Dependency properties

    public static readonly DependencyProperty ShowContentProperty = DependencyProperty.Register(
        nameof(ShowContent),
        typeof(bool),
        typeof(ConditionalContentControl),
        new FrameworkPropertyMetadata
        {
            AffectsArrange = true,
            AffectsMeasure = true,
            DefaultValue = false,
        });

    public bool ShowContent
    {
        get => (bool)GetValue(ShowContentProperty);
        set => SetValue(ShowContentProperty, value);
    }

    #endregion
}

用法:

<StackPanel>
    <CheckBox x:Name="CB" Content="Show content" />
    <local:ConditionalContentControl ShowContent="{Binding ElementName=CB, Path=IsChecked}">
        <Border Background="Red" Height="200" />
    </local:ConditionalContentControl>
</StackPanel>

請注意,盡管這種方法有其缺點,例如,如果未立即加載內容,則與相對源的綁定將報告錯誤。

我決定發表我的嘗試作為答案:

public class DynamicContent : ContentControl
{
    public bool ShowContent
    {
        get { return (bool)GetValue(ShowContentProperty); }
        set { SetValue(ShowContentProperty, value); }
    }
    public static readonly DependencyProperty ShowContentProperty =
        DependencyProperty.Register("ShowContent", typeof(bool), typeof(DynamicContent),
        new PropertyMetadata(false,
            (sender, e) => ((DynamicContent)sender).ChangeContent((bool)e.NewValue)));

    protected override void OnContentChanged(object oldContent, object newContent)
    {
        base.OnContentChanged(oldContent, newContent);
        ChangeContent(ShowContent);
    }

    void ChangeContent(bool show) => Template = show ? (ControlTemplate)Content : null;
}

簡短,清晰(是嗎?)並且可以正常工作。

想法是使用ContentControl.Content來指定控件模板,並更改ShowContentContent (以支持設計時)值時顯示/隱藏控件Template

測試示例(包括相對和名稱綁定):

<StackPanel Tag="Test">
    <CheckBox x:Name="comboBox"
              Content="Show something"
              IsChecked="{Binding ShowSomething}" />
    <local:DynamicContent ShowContent="{Binding IsChecked, ElementName=comboBox}">
        <ControlTemplate>
            <local:MyCheckBox IsChecked="{Binding IsChecked, ElementName=comboBox}"
                      Content="{Binding Tag, RelativeSource={RelativeSource AncestorType=StackPanel}}" />
        </ControlTemplate>
    </local:DynamicContent>
</StackPanel>

要查看延遲的內容:

public class MyCheckBox : CheckBox
{
    public MyCheckBox()
    {
        Debug.WriteLine("MyCheckBox is constructed");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM