基于MVVM的项目绑定到两个Windows Phone控件

本文关键字:两个 Windows 控件 Phone MVVM 项目 绑定 基于 | 更新日期: 2023-09-27 18:09:30

我在一个页面上有两个控件:
1. RadSlider
2. 列表框

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="100"></RowDefinition>
        </Grid.RowDefinitions>
        <telerik:RadSlideView Name="imgSlidView" >
        <telerik:RadSlideView.ItemTemplate>
            <DataTemplate>
                <Image  Source="{Binding Src}"></Image>
            </DataTemplate>
            </telerik:RadSlideView.ItemTemplate>
            <telerik:RadSlideView.ItemPreviewTemplate>
                <DataTemplate>
                    <telerik:RadBusyIndicator></telerik:RadBusyIndicator>
                </DataTemplate>
            </telerik:RadSlideView.ItemPreviewTemplate>
        </telerik:RadSlideView>
        <ListBox Grid.Row="1" Name="lstImage">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"></StackPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Image Height="100" Margin="0,0,5,0" Source="{Binding Src}"></Image>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我想把两个控件绑定到一个单一的项目源,这样如果一个的选择改变了其他的选择也应该改变。
我对基于MVVM的解决方案感兴趣。我的代码:

 class CategoryViewModel : ViewModelBase
{
    public ObservableCollection<ImageSource> ImageCollection { get; set; }
    private ImageSource _CurrentImage;
    public ImageSource CurrentImage
    {
        get { return _CurrentImage; }
        set
        {
            _CurrentImage = value;
            RaisePropertyChanged("CurrentImage");
        }
    }
}

除此之外,我还有一段返回IEnumerable的代码,我想把它作为Item Source。

 public static async Task<IEnumerable<Object>> GetCategoryNames()
    {
        if (Categories == null)
        {
            JDir dir = Newtonsoft.Json.JsonConvert.DeserializeObject<JDir>(await LoadFromJson());
            Categories = ConvertJDirToCategory(dir);
            return Categories.Select(p => new { Name = p.Name, Src = "Images/" + p.Name + ".jpg" });
        }
        else
        {
            return Categories.Select(p => new { Name = p.Name, Src = "Images/" + p.Name + ".jpg" });
        }
    }

我做得对吗?我该怎么做?

提前感谢!

EDIT - from comments:

private static async Task<string>   LoadFromJson()
{
    string theData = string.Empty; 
    StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///data.json"));  
    using (StreamReader streamReader = new StreamReader(await file.OpenStreamForReadAsync()))             
    {
        return await streamReader.ReadToEndAsync();         
    }        
}

基于MVVM的项目绑定到两个Windows Phone控件

谢谢大家,我的问题现在已经解决了:

XAML:

DataContext="{Binding Category, Source={StaticResource Locator}}"

两个控件:

     <telerik:RadSlideView Name="imgSlidView" SelectedItem="{Binding SelectedItem,Mode=TwoWay}" ItemsSource="{Binding Images}">
            <telerik:RadSlideView.ItemTemplate>
                <DataTemplate>
                    <Image  Source="{Binding}">
                        <telerik:RadContextMenu.ContextMenu>
                            <telerik:RadContextMenu IsZoomEnabled="False"  OpenGesture="Tap">
                                <telerik:RadContextMenuItem  Tap="RadContextMenuItem_Tap" Content="Share">
                                </telerik:RadContextMenuItem>
                            </telerik:RadContextMenu>
                        </telerik:RadContextMenu.ContextMenu>
                    </Image>
                </DataTemplate>
            </telerik:RadSlideView.ItemTemplate>
            <telerik:RadSlideView.ItemPreviewTemplate>
                <DataTemplate>
                    <telerik:RadBusyIndicator></telerik:RadBusyIndicator>
                </DataTemplate>
            </telerik:RadSlideView.ItemPreviewTemplate>
        </telerik:RadSlideView>
        <ListBox Grid.Row="1" ScrollViewer.HorizontalScrollBarVisibility="Auto" Name="lstImage" SelectedItem="{Binding SelectedItem,Mode=TwoWay}" ItemsSource="{Binding Images}">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"></StackPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Image Height="100" Margin="0,0,5,0" Source="{Binding}">
                    </Image>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

视图模型:

 public class CategoryViewModel : ViewModelBase
{
    private string _CategoryName;
    public string CategoryName
    {
        get { return _CategoryName; }
        set
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() => { Set<string>(ref _CategoryName, value); });
        }
    }
    private Uri _SelectedItem;
    public Uri SelectedItem
    {
        get { return _SelectedItem; }
        set
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() => { Set<Uri>(ref _SelectedItem, value); });
        }
    }

    private ObservableCollection<Uri> _Images;
    public ObservableCollection<Uri> Images
    {
        get { return _Images; }
        set { Set<ObservableCollection<Uri>>(ref _Images, value); }
    }
    public CategoryViewModel()
    {
        CategoryName = string.Empty;
        Images = new ObservableCollection<Uri>();
    }
}

XAML.cs

 protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        string Category = string.Empty;
        NavigationContext.QueryString.TryGetValue("category", out Category);
        if (this.DataContext is CategoryViewModel)
        {
            var vm = (CategoryViewModel)this.DataContext;
            vm.Images.Clear();
            JSONHelper.LoadFromJson().ContinueWith(t =>
            {
                vm.CategoryName = Category;
                var images = t.Result.Dirs.FirstOrDefault(p => p.DirName == Category).Files;
                Dispatcher.BeginInvoke(() =>
                {
                    foreach (var img in images)
                    {
                        vm.Images.Add(new Uri(string.Format("Data/{0}/{1}", Category, img), UriKind.Relative));
                    }
                });
            });
        }
    }