wpf自定義控制元件包含圖片元素時,圖片無法顯示
設計時無法預覽圖片,編譯啟動后圖片可以顯示
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp2">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Image x:Name="ButtonImage"
Source="/img/sz.png"
Height="{Binding ImageSize, RelativeSource={RelativeSource TemplatedParent}}"
Width="{Binding ImageSize, RelativeSource={RelativeSource TemplatedParent}}"
ToolTip="{TemplateBinding ToolTip}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp2
{
/// <summary>
/// 按照步驟 1a 或 1b 操作,然后執行步驟 2 以在 XAML 檔案中使用此自定義控制元件。
///
/// 步驟 1a) 在當前專案中存在的 XAML 檔案中使用該自定義控制元件。
/// 將此 XmlNamespace 特性添加到要使用該特性的標記檔案的根
/// 元素中:
///
/// xmlns:MyNamespace="clr-namespace:WpfApp2"
///
///
/// 步驟 1b) 在其他專案中存在的 XAML 檔案中使用該自定義控制元件。
/// 將此 XmlNamespace 特性添加到要使用該特性的標記檔案的根
/// 元素中:
///
/// xmlns:MyNamespace="clr-namespace:WpfApp2;assembly=WpfApp2"
///
/// 您還需要添加一個從 XAML 檔案所在的專案到此專案的專案參考,
/// 并重新生成以避免編譯錯誤:
///
/// 在解決方案資源管理器中右擊目標專案,然后依次單擊
/// “添加參考”->“專案”->[瀏覽查找并選擇此專案]
///
///
/// 步驟 2)
/// 繼續操作并在 XAML 檔案中使用控制元件。
///
/// <MyNamespace:CustomControl1/>
///
/// </summary>
public class CustomControl1 : Control
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
public double ImageSize
{
get { return (double)GetValue(ImageSizeProperty); }
set { SetValue(ImageSizeProperty, value); }
}
public static readonly DependencyProperty ImageSizeProperty = DependencyProperty.Register("ImageSize", typeof(double), typeof(CustomControl1),
new FrameworkPropertyMetadata(30.0, FrameworkPropertyMetadataOptions.AffectsRender));
public string NormalImagePath
{
get { return (string)GetValue(NormalImagePathProperty); }
set { SetValue(NormalImagePathProperty, value); }
}
public static readonly DependencyProperty NormalImagePathProperty = DependencyProperty.Register("NormalImagePath", typeof(string), typeof(CustomControl1),
new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsRender));
}
}
<local:CustomControl1 NormalImagePath="/img/sz.png" ImageSize="30" RenderTransformOrigin="0.5,0.5" Width="20" Height="20" Margin="475,205,297,194"/>

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/34560.html
標籤:C#
