2

我正在制作一个应用程序,您在底部有一个列表框,上面有不同网站的徽标,WebBrowser顶部有一个。这个想法是,当您按下徽标时,webBrowser 会加载相应的页面。我已经完成了这项工作,但我想用 MVVM 重新制作应用程序以使其更好。WebBrowser我已经制作了包含所有徽标的列表框,但是当我单击徽标时,我不知道如何将 URL 加载到列表框上。

4

2 回答 2

7

不是 100% 确定这是否适用于 Phone7,但值得一试……

拳头WebBrowserSource 属性不可绑定,因为它不是 a DependancyProperty,因此您必须创建一个帮助器类来创建AttachedProperty帮助绑定。

然后,您可以使用包含来自您的 ListBoxItem 的实际链接的属性将您链接ListBox SelectedItem到新属性。LinkSource

例子:

xml:

<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>

代码:

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;
        }
    }

}

结果:

在此处输入图像描述

于 2013-01-28T00:57:08.020 回答
-1

你的问题实际上是两个问题。

  1. 有几种方法可以从列表框中获取点击。最基本的一个是<Listbox SelectedItem="{Binding selectedItem,mode=TwoWay}" ...

  2. 要设置 Web 浏览器的 URL,您可以在 VM 中实现 INotifyPropertyChanged,public Uri browserUri { get; private set; }在 WM 中声明,确保在更改属性时引发 PropertyChanged,在 XAML 中<WebBrowser Source="{Binding browserUri}" />

于 2013-01-28T00:19:55.490 回答