簡體   English   中英

WPF在運行時在C#代碼中為按鈕設置圖像

[英]WPF set image for a button in the C# code behind at runtime

我是WPF的新手,所以請多多包涵。

基本上,我已經在WPF用戶控件中定義了一種樣式,以顯示帶有圖像的按鈕,如下所示:

<UserControl.Resources>
    <Style TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <TextBlock  HorizontalAlignment="Center" VerticalAlignment="Center">
                        <Image Width="16" Height="16" Stretch="UniformToFill"/>
                        <ContentPresenter/>
                    </TextBlock>
                </ControlTemplate>
            </Setter.Value>

        </Setter>
    </Style>
</UserControl.Resources>

然后,我在運行時將按鈕的負載添加到網格中(由於按鈕的數量和類型是動態的,因此必須在運行時)。

我也想在運行時設置按鈕的圖像。 我嘗試了多種方法,但是似乎都沒有用。 在Xaml中設置源工作正常。 我正在嘗試的代碼如下:

Button b = new Button();
// Create source.
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(@"C:\SourceCode\DSA\DSALibrary\Icons\money.png");
bi.EndInit();

b.SetValue(Image.SourceProperty, bi);

任何人都可以指出我出了問題的地方,如果我想猜的話,我會說我認為自己正在設定價值的地方,但實際上我沒有。

干杯

您可以嘗試使用Button的Content屬性,並聲明一個DataTemplate來處理內容:

<UserControl.Resources>
    <Style TargetType="Button">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Width="16" Height="16" Stretch="UniformToFill" Source="{Binding}"/>
                        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="My button text" />
                    </StackPanel>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <ContentPresenter/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</UserControl.Resources>

在按鈕的內容上設置BitmapImage,等等:)

您可以確認這是您正在創建的System.Windows.Controls.UserControl派生對象嗎?

我的猜測是,控件在創建時會加載位圖,因此在設置位圖源屬性后不會被捕獲。 在進行第二階段之前,您是否嘗試過以編程方式創建包含兩個階段的按鈕並進行設置?

您可以嘗試調用按鈕的Invalidate()函數以確保其重繪。

暫無
暫無

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

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