WPF - 设置WebBrowser无法正常工作的代码可见性

时间:2017-04-18 05:10:20

标签: c# wpf xaml visibility

我有两个元素,一个WebBrowser和一个Slider,我试图隐藏一个并显示另一个,具体取决于用户打开的文档类型,PDF或视频文件(mp4)。但是,目前,当我打开PDF文件时,WebBrowser仍然是隐藏的。

在MainWindow.xaml中,我有

<WebBrowser x:Name="PDFView" Width="600" 
                    Height="410" Visibility="{Binding PDFVisible}">
</WebBrowser>

<FFmpegFramework:MediaElement Grid.Row="0" x:Name="MediaElement"
                    Height="400" Background="Gray"  Visibility="{Binding VideoVisible}"/>

在MainWindow.xaml.cs中,我有

else if (fileName.Contains("pdf"))
{

    MainWindowViewModel dataContext = this.DataContext as MainWindowViewModel;
    dataContext.PDFVisible = Visibility.Visible;
    dataContext.VideoVisible = Visibility.Collapsed;

    //PDFView.Navigate("file:///" + fileName);
}
else if (fileName.Contains("mp4"))
{
    MainWindowViewModel dataContext = this.DataContext as MainWindowViewModel;
    dataContext.PDFVisible = Visibility.Collapsed;
    dataContext.VideoVisible = Visibility.Visible;
}

在MainWindowModel.cs中,我有:

public Visibility PDFVisible
{
    get
    {
        return fPDFVisible;
    }
    set
    {
        this.SetProperty<Visibility>(ref fPDFVisible, value);
    }
}

public Visibility VideoVisible
{
    get
    {
        return fVideoVisible;
    }
    set
    {
        this.SetProperty<Visibility>(ref fVideoVisible, value);
    }
}

private Visibility fPDFVisible = Visibility.Collapsed;
private Visibility fVideoVisible = Visibility.Visible;

1 个答案:

答案 0 :(得分:0)

您在.xaml.cs文件中进行此更改,而不是为什么要创建objects来更改visibility。您可以通过控件名称直接更改visibility

if (fileName.Contains("pdf"))
{
    PDFView.Visibility = Visibility.Visible;
    MediaElement.Visibility = Visibility.Collapsed;
}
else if (fileName.Contains("mp4"))
{
    PDFView.Visibility = Visibility.Collapsed;
    MediaElement.Visibility = Visibility.Visible;
}

并且不要忘记更改&#39; Mode = TwoWay&#39;在约束力。它还会更改ViewModel

中的属性
<WebBrowser x:Name="PDFView" Width="600" 
            Height="410" Visibility="{Binding PDFVisible, Mode=TwoWay}" />

<FFmpegFramework:MediaElement Grid.Row="0" x:Name="MediaElement"
                 Height="400" Background="Gray"  Visibility="{Binding VideoVisible, Mode=TwoWay}" />