【发布时间】:2011-04-10 01:36:51
【问题描述】:
在下面的 XAML UserControl 中,我将一些项目绑定到 UserControl 的链接类中的属性。
<UserControl x:Class="Kiosk.EventSelectButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Kiosk"
Height="130" Width="130">
<Grid>
<Button
Style="{DynamicResource DarkButton130x130}"
HorizontalAlignment="Left"
VerticalAlignment="Center">
<Grid Margin="0,0,0,0" Height="118" Width="118">
<Image VerticalAlignment="Top" HorizontalAlignment="Center" Source="image/select_button_arrows.png" />
<Image x:Name="EventImageComponent" VerticalAlignment="Center" HorizontalAlignment="Center" Effect="{DynamicResource KioskStandardDropShadow}" Source="{Binding Path=EventImage}" />
<TextBlock x:Name="SelectTextBlock" Text="{Binding Path=SelectText}" VerticalAlignment="Top" HorizontalAlignment="Center" Margin="0,-2,0,0" FontSize="10pt" Foreground="#5aaff5" />
<TextBlock x:Name="LabelTextBlock" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="0,0,0,0" FontSize="14pt" FontWeight="Bold" Text="{Binding Path=Label}"/>
</Grid>
</Button>
</Grid>
</UserControl>
在链接类的构造函数中,我将项目的 DataContext 应用到 this,如下所示。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 Kiosk
{
/// <summary>
/// Interaction logic for EventSelectButton.xaml
/// </summary>
public partial class EventSelectButton : UserControl
{
public String ValueContainer;
private String _EventImage;
public String EventImage
{
get
{
return _EventImage;
}
set
{
_EventImage = value;
}
}
private String _Label;
public String Label
{
get
{
return _Label;
}
set
{
_Label = value;
}
}
private String _SelectText;
public String SelectText
{
get
{
return _SelectText;
}
set
{
_SelectText = value;
}
}
public EventSelectButton()
{
InitializeComponent();
LabelTextBlock.DataContext = this;
SelectTextBlock.DataContext = this;
EventImageComponent.DataContext = this;
}
}
}
编辑
虽然这可以按预期工作,但我很想知道是否有更简单的方法可以做到这一点。 (编辑,经验教训。)这实际上不会在初始化之后起作用,将设置公共属性,但是由于该类不使用 DependentProperties 或者实现 INotifyPropertyChanged,绑定将不起作用正如预期的那样。 (结束编辑)
例如,
- 我能否将 XAML 中这些项目的 DataContext 设置为 this(作为 EventSelectButton 实例),如果可以,如何设置?
- 或者,是否可以从 UserControl 父级继承 DataContext,从而使绑定路径更简单。
到目前为止,我发现的唯一替代方案更冗长,例如使用RelativeSource绑定方法定位EventSelectButton Ancestor。
所以,请告诉我可以改进此绑定表达式的任何方法,非常感谢任何关于在 UserComponent 中绑定的最佳实践的 cmets。
【问题讨论】:
标签: wpf xaml binding user-controls