【问题标题】:X:bind throw NullReferenceException when using the ControlTemplateX:bind 在使用 ControlTemplate 时抛出 NullReferenceException
【发布时间】:2018-01-19 14:06:54
【问题描述】:

当我编写继承自按钮的 Button 时,我使用图像设置 ControlTemplate,源代码为 x:bind 到代码隐藏中的字符串属性,如下面的屏幕截图:

<Grid x:Name="rectangle1">
    <Image Source="{x:Bind aCheckImage}" //Error Here
            Stretch="UniformToFill"
            HorizontalAlignment="Center"
            VerticalAlignment="Center">
    </Image>
</Grid>

为什么它会在编译时抛出“对象引用未设置为对象的实例”的错误。如何解决?

【问题讨论】:

  • 通过编辑您的问题分享您的代码,并确保您的帖子格式正确。
  • aCheckImage的类型是什么?
  • @linxiao aCheckImage 应该是BitmapImage
  • 你能发布更多代码吗?您如何派生 muButton 以便您可以添加 xaml 作为代码隐藏。你有按钮的自定义模板吗?那么你应该使用 TemplateBinding。

标签: windows xaml uwp


【解决方案1】:

@Vijay Nirmal 给了我一个解决方法。

如果您想将图像源绑定到其他值,您应该在代码中确定您的值。我会写在下面。

    public static readonly DependencyProperty aCheckImageProperty = DependencyProperty.Register(
        "aCheckImage", typeof(BitmapSource), typeof(MainPage), new PropertyMetadata(default(BitmapSource)));

    public BitmapSource aCheckImage
    {
        get { return (BitmapSource) GetValue(aCheckImageProperty); }
        set { SetValue(aCheckImageProperty, value); }
    }

我应该在构造函数中设置它。

    public MainPage()
    {
        InitializeComponent();

        aCheckImage = new BitmapImage(new Uri("ms-appx:///Assets/LockScreenLogo.scale-200.png"));
    }

如果你想知道怎么写uri,请看https://msdn.microsoft.com/zh-cn/library/windows/apps/xaml/hh965322(v=win.10).aspx 然后我可以在 XAML 中绑定它。

    <Grid x:Name="rectangle1">
        <Image Source="{x:Bind aCheckImage}" 
               Stretch="UniformToFill"
               HorizontalAlignment="Center"
               VerticalAlignment="Center">
        </Image>
    </Grid>

【讨论】:

    猜你喜欢
    • 2020-10-25
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多