我有一些字符串属性需要解析内容,并显示在单独的控件中。假设有电子邮件和网址用空格分隔。显示电子邮件工作正常,但网址却不行。这是代码:
XAML 文件:
<ScrollViewer Grid.Row="0" Grid.Column="5" >
<StackPanel Orientation="Vertical">
<TextBox Name="EmailTextBox"
Text="{Binding ElementName=candidatePersonalDataViewControl, Mode=OneWay, Path=Candidate.Email, Converter={StaticResource emailConverter}}"/>
<ItemsControl ItemsSource="{Binding ElementName=candidatePersonalDataViewControl, Mode=OneWay, Path=UrlsProperty}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock
Margin="0,0,0,0"
Padding="5,2,5,2"
HorizontalAlignment="Left"
VerticalAlignment="Top">
<Hyperlink NavigateUri="{Binding Path=/}"
Click="EmailAsWWW_Click">
<Run Text="{Binding Path=/}" />
</Hyperlink>
</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</StackPanel>
</ScrollViewer>
C# 文件:
private static readonly DependencyProperty CandidateProperty = DependencyProperty.Register("Candidate", typeof(Candidate), typeof(CandidatePersonalDataViewControl));
public Candidate Candidate
{
get { return (Candidate)GetValue(CandidateProperty); }
set { SetValue(CandidateProperty, value); }
}
public CandidatePersonalDataViewControl()
{
InitializeComponent();
this.DataContext = this;
UrlsProperty = new ObservableCollection<string>();
}
public ObservableCollection<string> UrlsProperty
{
get;
private set;
}
private void Grid_LayoutUpdated(object sender, EventArgs e)
{
if (Candidate == null)
return;
if (Candidate.Email == null)
return;
EmailPropertyToEmailsConverter emailConverter = new EmailPropertyToEmailsConverter();
bool emails = (emailConverter.Convert(Candidate.Email, typeof(string), null, null) as string) != null;
this.EmailTextBox.Visibility = emails ? Visibility.Visible : Visibility.Collapsed;
EmailPropertyToUrlListConverter urlConverter = new EmailPropertyToUrlListConverter();
IList<string> urls = urlConverter.Convert(Candidate.Email, typeof(string), null, null) as IList<string>;
UrlsProperty.Clear();
if (urls != null)
foreach (string url in urls)
UrlsProperty.Add(url);
}
我已经调试了 Grid_LayoutUpdated 并且工作正常。它会在需要时触发,并且 UrlsCollection 包含所需的数据。正如我所说,EmailTextBox 显示数据,但 ItemsControl 一直是空的。更有趣的是,从超链接绑定中删除“Path=/”会引发 XAML Parse 异常。我的想法已经用完了......我已经阅读了一些主题,但没有一个有用