C# Wpf自定义按钮图标和文本从代码更改
所以我会变矮。我想从另一个项目中的代码中使用编译后的.dll设置textBlock x:Name=ButtonText和Images x:Name=LeftIcon和x:Name=rightcon XAML: 当前,如果我从代码中将一个新的文本块附加到我的按钮实例,它不会显示。。。图像也一样。我错过了什么C# Wpf自定义按钮图标和文本从代码更改,c#,wpf,xaml,C#,Wpf,Xaml,所以我会变矮。我想从另一个项目中的代码中使用编译后的.dll设置textBlock x:Name=ButtonText和Images x:Name=LeftIcon和x:Name=rightcon XAML: 当前,如果我从代码中将一个新的文本块附加到我的按钮实例,它不会显示。。。图像也一样。我错过了什么 谢谢你的帮助…: actionButton类应该为两个图像和文本声明可绑定的依赖属性 左图的示例如下所示。属性类型为ImageSource,因为这是图像控件的源属性的类型。您必须为正确的图像声
谢谢你的帮助…: actionButton类应该为两个图像和文本声明可绑定的依赖属性 左图的示例如下所示。属性类型为ImageSource,因为这是图像控件的源属性的类型。您必须为正确的图像声明第二个属性,为TextBlock文本声明string类型的属性
public static readonly DependencyProperty LeftImageProperty =
DependencyProperty.Register(
nameof(LeftImage), typeof(ImageSource), typeof(actionButton));
public ImageSource LeftImage
{
get { return (ImageSource)GetValue(LeftImageProperty); }
set { SetValue(LeftImageProperty, value); }
}
在按钮的XAML中,您将使用具有RelativeSource绑定的属性:
<TextBlock Text="{Binding Text,
RelativeSource={RelativeSource AncestorType=Button}}" ... />
<Image Source="{Binding LeftImage,
RelativeSource={RelativeSource AncestorType=Button}}" ... />
<Image Source="{Binding RightImage,
RelativeSource={RelativeSource AncestorType=Button}}" ... />
如果图像文件应作为程序集资源嵌入,则应将其生成操作设置为resource,并从以下位置加载:
请注意,您应该遵循广泛接受的命名约定,并将其命名为ActionButton。谢谢!它像一个符咒一样工作经过一些修改:
public static readonly DependencyProperty LeftImageProperty =
DependencyProperty.Register(
nameof(LeftImage), typeof(ImageSource), typeof(actionButton));
public ImageSource LeftImage
{
get { return (ImageSource)GetValue(LeftImageProperty); }
set { SetValue(LeftImageProperty, value); }
}
<TextBlock Text="{Binding Text,
RelativeSource={RelativeSource AncestorType=Button}}" ... />
<Image Source="{Binding LeftImage,
RelativeSource={RelativeSource AncestorType=Button}}" ... />
<Image Source="{Binding RightImage,
RelativeSource={RelativeSource AncestorType=Button}}" ... />
<Button x:Class="MyNamespace.actionButton"
...
xmlns:local="clr-namespace:MyNamespace">
<Button.Template>
<ControlTemplate TargetType="local:actionButton">
...
<Image Source="{TemplateBinding LeftImage}" ... />
...
</ControlTemplate>
</Button.Template>
</Button>
<local:ActionButton x:Name="ab" LeftImage="SomeImage.jpg"/>
ab.LeftImage = new BitmapImage(new Uri("SomeImage.jpg", UriKind.RelativeOrAbsolute));
ab.LeftImage = new BitmapImage(new Uri("pack://application:,,,/SomeImage.jpg"));