【问题标题】:Binding an Image using XAML and ImageSource使用 XAML 和 ImageSource 绑定图像
【发布时间】:2018-07-07 12:53:43
【问题描述】:

我有一个媒体播放器元素,它使用 PosterSource(如 ImageSource)作为我正在开发的 UWP 应用程序。代码如下所示:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <MediaPlayerElement x:Name="MainMPE" AreTransportControlsEnabled="True" AutoPlay="True" PosterSource="{Binding PosterSource}">
    </MediaPlayerElement>
</Grid>

在我的代码中,我对PosterSource 进行了以下设置

public sealed partial class PlayerView : Page, INotifyPropertyChanged
{
    private ImageSource _PosterSource;

    public event PropertyChangedEventHandler PropertyChanged;

    public ImageSource PosterSource
    {
        get => _PosterSource;
        set
        {
            if (_PosterSource != value)
            {
                _PosterSource = value;
                RaisePropertyChanged(nameof(PosterSource));
            }
        }
    }

    private async void PlayerView_Loaded(object sender, RoutedEventArgs e)
    {
        await SetPoster();
        // other code to load PlayerView
    }

    private async Task SetPoster()
    {
        var tempBitamp = new BitmapImage();
        await tempBitamp.SetSourceAsync(/* Stream comes from anotehr object */);
        PosterSource = tempBitamp;
    }

    private void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

我的问题是它没有更新。图像永远不会加载。如果我直接从代码中调用 MainMPE.PosterSource 对象并将其设置为我的 BitmapImage,它可以工作,但我试图让它与 Bindings 一起正常运行。我在这里做错了什么?

【问题讨论】:

    标签: c# xaml binding uwp


    【解决方案1】:

    我在您的代码中唯一缺少的可能是一个问题是设置您页面的DataContext。与x:Bind 语法相反,您需要设置应该从中获取绑定的“上下文”。因此,如果您想在页面的代码隐藏中使用{Binding},可以在页面构造函数中的InitializeComponent 调用之后添加以下行:

    DataContext = this;
    

    之后它应该会按预期工作。

    更好的解决方案

    UWP 为数据绑定带来了更好的语法 - x:Bind。这种投标的优点是它摆脱了Binding 背后发生的所有反射,而是在编译时以强类型的方式完成。此外,它不考虑 DataContext 并直接绑定到页面的代码隐藏。唯一需要注意的是,默认情况下,x:Bind 仅是 OneTime,因此如果要更新绑定属性的值,则必须手动将其模式设置为 OneWay

    <MediaPlayerElement x:Name="MainMPE"
            AreTransportControlsEnabled="True" 
            AutoPlay="True" 
            PosterSource="{x:Bind PosterSource, Mode=OneWay}">
    </MediaPlayerElement>
    

    Binding 的更多选择

    顺便说一句,还有更多方法可以设置DataContext。您也可以在页面的 XAML 代码中执行此操作:

    <Page ... DataContext="{Binding Source={RelativeSource Self}}">
    

    或结合x:Name:

    <Page ... x:Name="Page" DataContext="{Binding ElementName=Page}">
    

    这两种方式都会将DataContext 设置为Page 实例本身。

    【讨论】:

    • 非常感谢,马丁!我在研究我的解决方案时确实阅读了有关 x:Bind 的信息,但由于不使用 Mode=OneWay 而遇到了同样的问题。这个解决方案效果很好!
    • 太棒了:-),编码愉快!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    相关资源
    最近更新 更多