简体   繁体   中英

Binding in UserControl

I have a UserControl that has an Image and a Textblock, like so:

<Image Stretch="UniformToFill" Source="{Binding Path=ImageURL}"/>
<TextBlock Text="{Binding Path=Title}"/>

in the .cs of the user control i have Dependency properties to make the binding:

    public string Title
    {
        get { return (string)GetValue(TitleProperty); }
        set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register("Title", typeof(string), typeof(MyUserControl), null);

    public string ImageURL
    {
        get { return (string)GetValue(ImageURLProperty); }
        set { SetValue(ImageURLProperty, value); }
    }

    public static readonly DependencyProperty ImageURLProperty =
        DependencyProperty.Register("ImageURL", typeof(string), typeof(MyUserControl), null);

    public MyUserControl()
    {
        this.InitializeComponent();
        (this.Content as FrameworkElement).DataContext = this;
    }

In my MainPage.xaml i call it inside a list

<ListView Grid.Row="1"
          HorizontalAlignment="Center"
          Name="ControlsListView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <controls:MyUserControl Margin="20"
                                  Title="{Binding Title}" //works
                                  ImageURL="{Binding ImageURL}"/> //doesn't work
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

And then i get this Data from Json.net and feed it to the ItemsSource of the ListView. It works just for the Title but no for the ImageURL, anyone could help me why?

Probably a bad DataContext, see ReSharper WPF error: "Cannot resolve symbol "MyVariable" due to unknown DataContext" . The answer describes how to use the free Snoop utility to detect runtime binding errors.

By default, the DataContext for a UserControl is not set to point at the code behind.

Add this:

<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">

Perhaps the backslashes in your ImageUrl are confusing things.

What ImageUrl are you using? Json might be interpreting the backslash as an escape character, and you might have to encode the ImageUrl using a double backslash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM