如何将UserControl绑定到ViewModel

时间:2013-12-10 16:44:55

标签: wpf c#-4.0 data-binding

我在连接两个组件时遇到了一些麻烦:

查看:

<UserControl x:Class="CoolPlaces.Views.ListItem"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    d:DesignHeight="480" d:DesignWidth="480">

    <ListBox ItemsSource="{Binding ListViewModel}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=Name, Mode=OneWay}" />
                    <TextBox Text="{Binding Path=Description, Mode=OneWay}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</UserControl>

主页面视图的一部分,其中包含上述用户控件:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <views:ListItem Height="300" />
</Grid>

视图模型:

namespace CoolPlaces.ViewModels
{
    public class ListViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<BasicModel> _places;

        public ObservableCollection<BasicModel> Places {
            get {
                return _places;
            }
            set {
                _places = value;
                RaisePropertyChanged("Places");
            }
        }

        public ListViewModel() { 
            Places = new ObservableCollection<BasicModel>(_loadPlaces());
        }

        private IEnumerable<BasicModel> _loadPlaces() {
            return //some hard coded objects
        }
    }
}

的MainPage

namespace CoolPlaces
{
    public partial class MainPage : PhoneApplicationPage
    {
        private ListViewModel vm;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            vm = new ListViewModel();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

你很亲密。您需要将DataContext设置为等于ViewModel。

public partial class MainPage : PhoneApplicationPage
{
    private ListViewModel vm;

    // Constructor
    public MainPage()
    {
        InitializeComponent();
        DataContext = vm = new ListViewModel();
    }
}

然后你的ListBox不需要绑定它。而是将其绑定到ViewModel上的Places属性:

<ListBox ItemsSource="{Binding Places}">