Seb*_*les 2 c# mvvm windows-phone-7
我正在制作一个应用程序,其中你有一个列表框,其中包含不同网站的徽标,并且WebBrowser顶部有一个.我们的想法是,当您按下徽标时,webBrowser会加载相应的页面.我已经完成了这项工作,但我想用MVVM重新制作应用程序以使其更好.我已经制作了包含所有徽标的列表框,但我不知道如何WebBrowser在点击徽标时加载URL .
不是100%肯定这是否适用于Phone7但值得一试......
关闭WebBrowserSource属性是不可绑定的,因为它不是一个DependancyProperty所以你必须创建一个帮助类来创建一个AttachedProperty帮助绑定.
然后,您可以使用包含ListBoxItem中实际链接的Property将您链接ListBox SelectedItem到新LinkSource属性.
例:
XAML:
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication8"
Title="MainWindow" Height="233" Width="405" Name="UI">
<StackPanel Orientation="Horizontal" DataContext="{Binding ElementName=UI}">
<ListBox x:Name="listbox" ItemsSource="{Binding Links}" Width="100" DisplayMemberPath="Name"/>
<WebBrowser local:WebBrowserHelper.LinkSource="{Binding ElementName=listbox, Path=SelectedItem.Site}" Width="200"/>
</StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)
码:
public partial class MainWindow : Window
{
private ObservableCollection<Link> _links = new ObservableCollection<Link>();
public MainWindow()
{
InitializeComponent();
Links.Add(new Link { Name = "StackOverflow", Site = new Uri("http://stackoverflow.com/") });
Links.Add(new Link { Name = "Google", Site = new Uri("http://www.google.com/") });
}
public ObservableCollection<Link> Links
{
get { return _links; }
set { _links = value; }
}
}
// ListBox item
public class Link
{
public string Name { get; set; }
public Uri Site { get; set; }
}
// helper calss to create AttachedProperty
public static class WebBrowserHelper
{
public static readonly DependencyProperty LinkSourceProperty =
DependencyProperty.RegisterAttached("LinkSource", typeof(string), typeof(WebBrowserHelper), new UIPropertyMetadata(null, LinkSourcePropertyChanged));
public static string GetLinkSource(DependencyObject obj)
{
return (string)obj.GetValue(LinkSourceProperty);
}
public static void SetLinkSource(DependencyObject obj, string value)
{
obj.SetValue(LinkSourceProperty, value);
}
// When link changed navigate to site.
public static void LinkSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var browser = o as WebBrowser;
if (browser != null)
{
string uri = e.NewValue as string;
browser.Source = uri != null ? new Uri(uri) : null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果:

| 归档时间: |
|
| 查看次数: |
6320 次 |
| 最近记录: |