我想使用由图像和标签组成的模板化 ComboBoxItems。如果我将模板分配给 ComboBoxItem,我可以以某种方式设置图像的源属性吗?目标是为不同的 ComboBoxItems 使用相同的模板,但在每个 Item 中使用不同的图片。
我还考虑过在模板中绑定 Image.Source-Property,但这失败了,因为“父”ComboBoxItem 当然没有我可以绑定的 Source-Property。
代码说明了我的问题:
<Style x:Key="ComboBoxPictureItem" TargetType="{x:Type ComboBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBoxItem">
<StackPanel Orientation="Horizontal">
<Image x:Name="StatusImage" />
<Label x:Name="StatusLabel" Content="Green"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ComboBox>
<ComboBoxItem Style="{StaticResource ResourceKey=ComboBoxPictureItem}"
-> sth. like: StatusImage.Source="PathToMyImage.png"/>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)
谢谢!
如果有一个带有DependencyProperty的自己的用户控件和相应的回调方法,如下所示:
public partial class PieChart : UserControl
{
public static readonly DependencyProperty RatesProperty = DependencyProperty.Register("Rates", typeof(ObservableCollection<double>), typeof(PieChart),
new PropertyMetadata(new ObservableCollection<double>() { 1.0, 1.0 }, new PropertyChangedCallback(OnRatesChanged)));
[...]
public static void OnRatesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((PieChart)d).drawChart();
}
Run Code Online (Sandbox Code Playgroud)
使用此用户控件时,我将名为"Rates"的ObservableCollection绑定到RatesProperty.费率和相关方法如下所示:
private ObservableCollection<double> rates;
public ObservableCollection<double> Rates
{
get { return this.rates; }
set
{
if (this.rates != value)
{
this.rates = value;
OnPropertyChanged("Rates");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new …Run Code Online (Sandbox Code Playgroud)