Why can't I use {x:Bind {RelativeSource Self}} in a data template?

前端 未结 2 1766
星月不相逢
星月不相逢 2021-01-03 02:25

If I use {x:Bind {RelativeSource Self}} in a data template, I get the following error while compiling:

Object reference not set to an ins

2条回答
  •  清歌不尽
    2021-01-03 02:56

    Although it seems you have solved your problem, I still want to make some clarifications to avoid confusion and make it clearly for future readers.

    As @Peter Duniho has mentioned, {x:Bind} can't work with DataContext property and {x:Bind} doesn't have a Source property, so you can't use StaticResource as data context in {x:Bind}, but you can use a property or a static path instead. While using {x:Bind}, it uses the background class as its data context. For example, when you set ItemsSource="{x:Bind NewsItems, Mode=OneWay}", it uses the XBindTest5.MainPage class as its data context and bind the NewsItems property of this class to ItemsSource. And while inside a DataTemplate, {x:Bind} uses the class declared in x:DataType as its data context. Please note following explanation in DataTemplate and x:DataType:

    Inside a DataTemplate (whether used as an item template, a content template, or a header template), the value of Path is not interpreted in the context of the page, but in the context of the data object being templated. So that its bindings can be validated (and efficient code generated for them) at compile-time, a DataTemplate needs to declare the type of its data object using x:DataType.

    In your case, you use the Command in DataTemplate, so you can add a OpenCommand property in NewsItem and bind this property to Command to use it.

    In your code-behind:

    public class NewsItem
    {
        public string Title { get; set; }
        public OpenItemCommand OpenCommand { get; set; }
    }
    

    In the XAML:

    
        
            
        
    
    

    Also {x:Bind} doesn't support {RelativeSource}, usually you can name the element and use its name in Path as an alternative. For more information see {x:Bind} and {Binding} feature comparison.

    But this can't be used in DataTemplate as all Path are supposed to be a property of NewsItem. And in your case, I think what you want to pass is the NewsItem not the Button, so you can use CommandParameter="{x:Bind}" to pass the NewsItem as the CommandParameter.

    PS: There is a small bug in XAML designer, you may still get a Object reference not set to an instance of an object. error. You can add a space after Bind like {x:Bind } as a workaround.

提交回复
热议问题