簡體   English   中英

如何在 WPF 中動態(通過代碼)添加在 XAML 中創建的自定義控件?

[英]How do you dynamically (via code) add custom Controls that were made in XAML in WPF?

我已經通過 Visual Stduio(和 Blend)構建了一個 XAML“模板”控件,當然它在 XAML 中。 當我搜索如何將控件動態添加到您的界面時,答案總是顯示動態構造控件然后添加它。 我的問題是如何添加一個已經制作好的控件。

總的來說,我對 WPF 和 C# 非常陌生。 也許我錯過了一些東西。 我開始認為我可以在 Visual Studio 中使用它的 GUI 創建界面,然后做后端代碼,但似乎還有更多我不理解的內容。 我正在嘗試設計一個基本上是“搜索縮略圖”的控件,或者換句話說,一個帶有圖像和文本框的彩色窗格。 我將圖像設置為空,將框文本設置為空,認為我可以在代碼中更改這些值。 我得到了一個搜索結果列表,並試圖為每個結果添加一個縮略圖控件,我假設是一個 WrapPanel(我不確定這是否正是我想要的,但我相信它是)。

這是我的帶有 XML 的縮略圖控件控制

<UserControl x:Class="ChaCha.SearchThumbnail"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:ChaCha"
         mc:Ignorable="d" 
         d:DesignHeight="250 " d:DesignWidth="150"
                              TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        Background="#FF3C3C3C"
    TextElement.FontWeight="Medium"
    TextElement.FontSize="14"
    FontFamily="pack://application:,,,/MaterialDesignThemes.Wpf;component/Resources/Roboto/#Roboto"
    >
<Grid x:Name="thumbnailGrid" Background="#FF004D40">
    <Image Source="{Binding thumbnailPath}" HorizontalAlignment="Left" Height="130" Margin="10,10,0,0" VerticalAlignment="Top" Width="130"/>
    <TextBlock x:Name="txt" HorizontalAlignment="Left" Margin="10,145,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="14" Height="95" Width="130" FontWeight="Normal" Text="{Binding thumbnailTxt}" TextAlignment="Center"/>

</Grid>

/// <summary>
/// Interaction logic for SearchThumbnail.xaml
/// </summary>
public partial class SearchThumbnail : UserControl
{

    public ImageSource ThumbnailPath { get; set; }
    public string ThumbnailTxt { get; set; }

    public SearchThumbnail()
    {
        InitializeComponent();
        DataContext = this;
    }
}

我知道這段代碼不符合 MVVM 格式的事情,但我只是在嘗試快速而骯臟的方法來快速解決這個問題。 一旦我對WPF更加滿意,我顯然會在將來將其更改為更受人尊敬的方法。

在 for 循環中獲取正確檢索的結果:

                    // Getting a compatible Image object for the SearchThumbnail image Pane. Code from another stack overflow thread
                    var imgUrl = new Uri(thumbnail);
                    var imageData = new WebClient().DownloadData(imgUrl);

                    var bitmapImage = new BitmapImage { CacheOption = BitmapCacheOption.OnLoad };
                    bitmapImage.BeginInit();
                    bitmapImage.StreamSource = new MemoryStream(imageData);
                    bitmapImage.EndInit();

                    // OBVIOUSLY FAILED LAST ATTEMPT HERE.
                    var thumb = new SearchThumbnail()
                    {
                    ThumbnailTxt = title,
                    ThumbnailPath = bitmapImage
                    };
                    this.wrapPanel.Children.Add(thumb);

我預計會完全失敗,但我將控件添加到我的主窗格中,我假設邊距為 0。 不顯示圖像,也不更改文本。

結果

UserControl 應該公開這樣的依賴屬性:

public partial class SearchThumbnail : UserControl
{
    public SearchThumbnail()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty ImageProperty = DependencyProperty.Register(
        nameof(Image), typeof(ImageSource), typeof(SearchThumbnail));

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
        nameof(Text), typeof(string), typeof(SearchThumbnail));

    public ImageSource Image
    {
        get { return (ImageSource)GetValue(ImageProperty); }
        set { SetValue(ImageProperty, value); }
    }

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
}

請注意,您不能在其構造函數中顯式設置 UserControl 的 DataContext,否則依賴屬性的任何標准 DataContext-based 綁定都將不起作用。

在其 XAML 中,您可以通過例如 RelativeSource Bindings 綁定到 UserControls 自己的屬性:

<UserControl ...>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Image Grid.Row="0"
            Source="{Binding Image, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
        <TextBlock Grid.Row="1"
            Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    </Grid>
</UserControl>

請注意,您創建 BitmapImage 的方式看起來很奇怪。 只要您有圖片 URL,這就足夠了:

var bitmapImage = new BitmapImage(imgUrl);

暫無
暫無

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

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