2012-08-25 5 views
0

아래의 첫 번째 블록에서 제 바인딩 구절 중 하나의 이름이 고의로 누락되어 두 번째 블록과 비교할 수 있습니다. 그 차이는 'ag2.item ...'행에 속성에서 찾을 수 없습니다.
항목은 내 모델입니다.
MVVM 바인딩 오류?

블록 2에서 내보기 모델 (ag2.viewModel.itemViewModel)을 가리키는 것을 볼 수 있습니다.

XAML 또는 내 코드 숨김에서 viewmodel이 아닌 내 클래스를 가리 키도록하려면 무엇을해야합니까?

블록 1 :

BindingExpression path error: 'itemModel1' property not found on 'ag2.item, ag2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. BindingExpression: Path='itemModel1' DataItem='ag2.item, ag2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'; target element is 'Windows.UI.Xaml.Controls.TextBlock' (Name='null'); target property is 'Text' (type 'String')

블록 2 : 뒤에

BindingExpression path error:'itemModel' property not found on 'ag2.viewModel.itemViewModel, ag2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. BindingExpression: Path='itemModel' DataItem='ag2.viewModel.itemViewModel, ag2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'; target element is 'Windows.UI.Xaml.Controls.TextBlock' (Name='null'); target property is 'Source' (type 'String')

코드 차단하기 위해 2 :

itemViewModel VM = new itemViewModel((Int32)navigationParameter); 
    DataContext = VM; 

또한해야 블록 1에서 나는 ItemSource="{Binding item}"이 설정된 GridView에 대한 제 바인딩을 수행하고 있습니다. 더 나은 이해를 얻기 위해 시도하는 노력의 일환으로 : Text="{Binding Path=itemModel}"

업데이트 :

블록 2에서 나는이를 사용하여 그리드 및 textblocks를 사용하여 내 UI를 만들었습니다. 내 코드를 거기에 넣고 있습니다. 아래는 ViewModel이고 그 아래는 내 모델입니다. XAML이 있습니다. MVVM이 새로 생겼으므로 내가 잘못하고있는 것을 실제로 알지 못합니다. 어떤 도움이라도 대단히 감사합니다.

XAML :

<common:LayoutAwarePage 
    x:Name="pageRoot" 
    x:Class="autoGarage2.VehicleItemDetailPage" 
    IsTabStop="false" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:common="using:autoGarage2.Common" 
    xmlns:local="using:autoGarage2" 
    xmlns:data="using:autoGarage2" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> 


    <!-- 
     This grid acts as a root panel for the page that defines two rows: 
     * Row 0 contains the back button and page title 
     * Row 1 contains the rest of the page layout 
    --> 
    <Grid Style="{StaticResource LayoutRootStyle}"> 

     <Grid.RowDefinitions> 
      <RowDefinition Height="140"/> 
      <RowDefinition Height="2*"/> 
     </Grid.RowDefinitions> 

     <!-- Back button and page title --> 
     <Grid 
     Style="{StaticResource LayoutRootStyle}" Grid.Row="0"> 

      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="Auto"/> 
       <ColumnDefinition Width="*"/> 
      </Grid.ColumnDefinitions> 
      <Button x:Name="backButton" Click="GoBack" IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}" Style="{StaticResource BackButtonStyle}"/> 
      <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource PageHeaderTextStyle}" Grid.Column="1"/> 
     </Grid> 



     <Grid Grid.Row="1"> 


      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="Auto"/> 
       <ColumnDefinition Width="*"/> 
      </Grid.ColumnDefinitions> 
      <Grid.RowDefinitions> 
       <RowDefinition Height="3*"/> 
       <RowDefinition Height="1*"/> 
      </Grid.RowDefinitions> 


       <StackPanel Grid.Row="0" Orientation="Horizontal" Width="auto" Margin="50,0,0,0" VerticalAlignment="Top" > 
        <Grid HorizontalAlignment="Left" Width="250" Height="250"> 
         <Border Background="White" BorderBrush="CornflowerBlue" BorderThickness="1"> 
           <Image Source="{Binding Image}" Margin="50"/> 
          </Border> 
          <StackPanel VerticalAlignment="Bottom" Background="CornflowerBlue"> 
           <StackPanel Orientation="Horizontal" DataContext="{Binding vehicles}"> 
           <TextBlock Text="{Binding VehicleMake}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource PageSubheaderTextStyle}" Margin="5"/> 
           <TextBlock Text="{Binding VehicleModel}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource PageSubheaderTextStyle}" Margin="5"/> 
           </StackPanel> 
          </StackPanel> 
         </Grid> 
       </StackPanel> 
        <StackPanel Grid.Row="0" Grid.Column="1"> 
         <Grid Margin="20,0,0,20"> 
          <Grid.RowDefinitions> 
           <RowDefinition Height="1*"/> 
           <RowDefinition Height="1*"/> 
           <RowDefinition Height="1*"/> 
           <RowDefinition Height="1*"/>         
           <RowDefinition Height="1*"/>         
           <RowDefinition Height="1*"/> 
           <RowDefinition Height="1*"/> 
           <RowDefinition Height="1*"/> 
           <RowDefinition Height="1*"/>         
           <RowDefinition Height="1*"/>  
           <RowDefinition Height="1*"/> 
           <RowDefinition Height="1*"/> 
           <RowDefinition/>         
          </Grid.RowDefinitions> 

          <Grid.ColumnDefinitions> 
           <ColumnDefinition Width="1*"/> 
           <ColumnDefinition Width="1*"/> 
           <ColumnDefinition Width="2*"/> 
          </Grid.ColumnDefinitions> 






          <TextBlock Text="Vehicle Make:" Grid.Row="0" Grid.Column="0" FontSize="25" Foreground="Black" /> 
          <TextBox Text="{Binding Path=VehicleMake}" Grid.Row="0" Grid.Column="1" FontSize="25" BorderBrush="CornflowerBlue" BorderThickness="1"/> 

          <TextBlock Text="Vehicle Model:" FontSize="25" Foreground="Black" Grid.Row="1" Grid.Column="0"/> 
          <TextBox Text="{Binding VehicleModel}" Grid.Row="1" Grid.Column="1" FontSize="25" BorderBrush="CornflowerBlue" BorderThickness="1"/>        

          <TextBlock Text="Vehicle Year:" FontSize="25" Foreground="Black" Grid.Row="2" Grid.Column="0"/> 
          <TextBox Text="{Binding VehicleYear}" Grid.Row="2" Grid.Column="1" FontSize="25" BorderBrush="CornflowerBlue" BorderThickness="1"/> 

          <TextBlock Text="License Plate:" FontSize="25" Foreground="Black" Grid.Row="3" Grid.Column="0"/> 
          <TextBox Text="" Grid.Row="3" Grid.Column="1" FontSize="25" BorderBrush="CornflowerBlue" BorderThickness="1"/> 

          <TextBlock Text="VIN #" FontSize="25" Foreground="Black" Grid.Row="4" Grid.Column="0"/> 
          <TextBox Text="" Grid.Row="4" Grid.Column="1" FontSize="25" BorderBrush="CornflowerBlue" BorderThickness="1" />  

          <TextBlock Text=" Current Mi/Km" FontSize="25" Foreground="Black" Grid.Row="5" Grid.Column="0"/> 
          <TextBox Text="" Grid.Row="5" Grid.Column="1" FontSize="25" BorderBrush="CornflowerBlue" BorderThickness="1"/>    

          <TextBlock Text="" FontSize="25" Foreground="Black" Grid.Row="6" Grid.ColumnSpan="2"/> 

          <TextBlock Text="Last Oil Change" FontSize="25" Foreground="Black" Grid.Row="7" Grid.Column="0"/> 
          <TextBox Text="" Grid.Row="7" Grid.Column="1" FontSize="25" BorderBrush="CornflowerBlue" BorderThickness="1"/>    

          <TextBlock Text="Last Oil Change Mi/Km" FontSize="25" Foreground="Black" Grid.Row="8" Grid.Column="0"/> 
          <TextBox Text="" Grid.Row="8" Grid.Column="1" FontSize="25" BorderBrush="CornflowerBlue" BorderThickness="1"/> 

          <TextBlock Text="" FontSize="25" Foreground="Black" Grid.Row="9" Grid.ColumnSpan="2"/> 

          <TextBlock Text="Reminder Mi/Km" FontSize="25" Foreground="Black" Grid.Row="10" Grid.Column="0"/> 
          <TextBox Text="" Grid.Row="10" Grid.Column="1" FontSize="25" BorderBrush="CornflowerBlue" BorderThickness="1"/>  

          <TextBlock Text="Reminder Month(s)" FontSize="25" Foreground="Black" Grid.Row="11" Grid.Column="0"/> 
          <TextBox Text="" Grid.Row="11" Grid.Column="1" FontSize="25" BorderBrush="CornflowerBlue" BorderThickness="1"/>       

         </Grid>      
       </StackPanel> 

      </Grid> 

    </Grid> 
</common:LayoutAwarePage> 

보기 모델 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Collections.ObjectModel; 
using Windows.Foundation.Collections; 
using System.IO; 


namespace autoGarage2.viewModel 
{ 
    class vehicleViewModel 
    { 
     private IList<vehicle> m_vehicles; 
     private IList<vehicle> m_vehicleItem; 

     public IList<vehicle> vehicles 
     { 
      get { return m_vehicles; } 
      set { m_vehicles = value; } 
     } 

     public IList<vehicle> vehicleItem 
     { 
      get { return m_vehicleItem; } 
      set { m_vehicleItem = value; } 
     } 

     private IList<vehicle> getVehicleDetail(Int32 vId) 
     { 
      var vehicleItem = 
       from v in vehicles 
       where v.VehicleId == vId 
       select v; 
      if (vId > 0) 
      { 
       //vehicles.Clear(); 
       m_vehicles = new List<vehicle>(); 
       foreach (var item in vehicleItem) 
       { 
        m_vehicles = new List<vehicle> 
        { 
         new vehicle(item.VehicleId, item.VehicleMake.ToString(), item.VehicleModel.ToString(), item.VehicleYear, item.Image.ToString()) 
        }; 
        //vehicle myVehicle = new vehicle(item.VehicleId, item.VehicleMake.ToString(), item.VehicleModel.ToString(), item.VehicleYear, item.Image.ToString()); 
        //m_vehicles.Add(myVehicle); 
       } 

      } 

      return m_vehicles; 
     } 

     public vehicleViewModel(Int32 vId) 
     { 
       m_vehicles = new List<vehicle> 
       {   
       new vehicle(1, "Mazda", "3", 2011, "Assets/car2.png"), 
       new vehicle(2, "Chevy", "Tahoe", 2004, "Assets/jeep1.png"), 
       new vehicle(3, "Honda", "Goldwing", 2007 ,"Assets/moto1.png") 
       }; 

       if (vId > 0) 
       { 
        //m_vehicles = new List<vehicle>(); 
        //m_vehicles = 
        //getVehicleDetail(vId); 
        m_vehicles = new List<vehicle> 
        {   
        new vehicle(2, "Chevy", "Tahoe", 2004, "Assets/jeep1.png"), 
        }; 

       } 
     } 



     #region dbCode 

     //string dbName = "vehicle.db"; 


     //var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, dbName);  
     //using (var db = new SQLite.SQLiteConnection(dbPath))  
     // { 
     //  var list = db.Table<vehicle>().ToList(); 
     //  m_vehicles = new List<vehicle>(); 
     //  for (Int32 i = 0; i < list.Count; i++) 
     //  { 
     //   //m_vehicles.Add(db.Table<vehicle>().ToList()); 
     //  } 
     // } 




     //foreach (vehicle item in m_vehicles) 
     //{ 
     // AllItems.Add(item); 
     //}  
     #endregion 

    } 
} 

모델 : 다른에 TextBlock를 데이터 바인딩하려고하는 것처럼

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
//using SQLite; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Media.Imaging; 

namespace autoGarage2 
{ 
    class vehicle : autoGarage2.Common.BindableBase 
    { 
     public vehicle() 
     { 
     } 

     public vehicle(string imagePath) 
     { 
      this._imagePath = imagePath; 
     } 
     public vehicle(Int32 vId, string vMake, string vModel, Int16 vYear, string imagePath) 
     { 
      this.m_vehicleID = vId; 
      this.m_vehicleMake = vMake; 
      this.m_vehicleModel = vModel; 
      this.m_vehicleYear = vYear; 
      this.m_vehicleName = vMake + " " + vModel; 
      this._imagePath = imagePath; 
     } 


     private Int32 m_vehicleID; 

     private String m_vehicleMake; 
     private String m_vehicleModel; 
     private Int16 m_vehicleYear; 
     private string m_vehicleName; 


     private ImageSource _image = null; 
     private String _imagePath = null; 
     private static Uri _baseUri = new Uri("ms-appx:///"); 

     //[AutoIncrement, PrimaryKey] 
     public Int32 VehicleId 
     { 
      get 
      { 
       return m_vehicleID; 
      } 
      set 
      { 
       m_vehicleID = value; 
       OnPropertyChanged("VehicleId"); 
      } 
     } 

     public String VehicleMake 
     { 
      get 
      { 
       return m_vehicleMake; 
      } 
      set 
      { 
       m_vehicleMake = value; 
       OnPropertyChanged("VehicleMake"); 
      } 
     } 

     public String VehicleModel 
     { 
      get 
      { 
       return m_vehicleModel; 
      } 
      set 
      { 
       m_vehicleModel = value; 
       OnPropertyChanged("VehicleModel"); 
      } 
     } 
    public Int16 VehicleYear 
    { 
     get 
     { 
      return m_vehicleYear; 
     } 
     set 
     { 
      m_vehicleYear = value; 
      OnPropertyChanged("VehicleYear"); 
     } 
    } 

    public string VehicleName 
    { 
     get 
     { 
      return m_vehicleName; 
     } 
     set 
     { 
      m_vehicleName = value; 
      OnPropertyChanged("VehicleName"); 
     } 
    } 

    public ImageSource Image 
    { 
     get 
     { 
      if (this._image == null && this._imagePath != null) 
      { 
       this._image = new BitmapImage(new Uri(vehicle._baseUri, this._imagePath)); 
      } 
      return this._image; 
     } 

     set 
     { 
      this._imagePath = null; 
      this.SetProperty(ref this._image, value); 
     } 
    } 

    public void SetImage(String path) 
    { 
     this._image = null; 
     this._imagePath = path; 
     this.OnPropertyChanged("Image"); 
    } 
} 

}

+0

당신이하고있는 일과 달성하고자하는 것이 조금 분명하지 않습니다. 뷰 모델의 구조는 무엇입니까? XAML의 구조는 무엇입니까? itemModel에 바인딩하려고합니까? itemModel은 어디에 정의되어 있습니까? –

+0

업데이트 된 질문을 참조하십시오. 나는 모든 것을 추가했다. 도움을 주시면 대단히 감사하겠습니다. – webdad3

+0

문제가 무엇인지 명확히하십시오. 위의 문제는 ItemModel과의 바인딩 오류를 참조하는 것으로 보입니다. 그러나 XAML의 ItemModel에 대한 바인딩이 없습니다. 어떤 TextBox가 오류를 일으키는 지, 그리고 무엇을 묶고 싶습니까? 뷰에 DataContext가 설정되어 있습니까? –

답변

0

내 데이터가 보이지 않는 주말 후에 나타나게 할 수있었습니다. 기본적으로 나는 autoGarage2.vehicles 목록에서 해당 속성을 찾을 수 없다는 바인딩 오류가 발생했다는 것을 알았습니다. 그래서 웃음을 지을 때 나는 다음과 같은 바인딩을 선행했습니다 :

{Binding vehicles[0].vehicleModel} 

다음 번에 데이터를 실행했을 때 데이터가있었습니다. 좀 더 생각한 후에는 차량의 단일 객체를 만들기로 결정했으며 목록 객체를 채우는 대신 단일 차량 속성 만 채우도록했습니다. 이제 저는 다음과 같이하고 있습니다 :

{Binding vehicleSingle.vehicleModel} 

모든 분들께 감사드립니다. 이것은 MVAM이 XAML에서 어떻게 작동하는지에 대한 미묘한 차이라고 생각합니다 ...

1

소리가 난다 객체가 아니라 ViewModel (윈도우/컨트롤의 DataContext)에 있습니다. 올바른지 확인하려면 TextBlock 또는 GridDataContext을 데이터 바인딩 할 개체로 설정해야합니다.

DataContext은 컨트롤의 DataBind 경로를 결정하는 데 사용되며 시각적 트리를 상속합니다. 따라서 DataContext이 MyViewModel로 설정되어 있고 Text="{Binding Path=itemModel}"을 사용하는 경우 바인딩 경로는 MyViewModel.itemModel이됩니다.

바인딩 경로에 MyViewModel을 포함하지 않으려면 문제가되는 컨트롤 또는 포함 된 컨트롤의 DataContext을 변경해야합니다. MVVM의 경우, 이는 종종 다른 객체를 ViewModel의 속성으로 드러내 기 때문에 수행됩니다.당신의 MyViewModel이 속성 ItemModel했다 그래서 경우 :

public class ItemModel 
{ 
    public string Property1 { get; } 
    public string Property2 { get; } 
} 

public class MyViewModel 
{ 
    public ItemModel ItemModel { get; private set; } 
} 

이 그런 다음 XAML은 다음과 같이 수를 (MyViewModel 가정하면 부모 윈도우/컨트롤의 DataContext에)입니다.

<Grid Grid.Row="1" DataContext="{Binding ItemModel}"> 
    <Grid.RowDefinitions> 
     <RowDefinition/> 
     <RowDefinition/> 
    </Grid.RowDefinitions> 
    <TextBlock Text="{Binding property1}"/> 
    <TextBlock Text="{Binding Property2}" Grid.Row="1"/> 
</Grid> 

두 개의 텍스트 상자는 ItemModel 개체의 Property1과 Property2에 바인딩됩니다.

+0

업데이트 된 질문을 참조하십시오. 잘만되면 내 코드가 내가 잘못하고있는 것을 식별하는 데 도움이되기를 바랍니다. – webdad3

1

목록에 바인딩하는 중이지만 XAML에서 ItemsControl을 사용하지 않는 것 같습니다. ListView와 같은 것을 사용하고 차량 또는 vehicleItem 목록에 ItemsSource을 바인딩하고 ItemTemplate/DataTemplate을 사용하여 컬렉션의 각 항목의 모양을 정의한 다음 컬렉션이 변경된 경우 ObservableCollection을 사용하거나 스왑하면 INotifyPropertyChanged.PropertyChanged 알림을 발생시켜야합니다. 귀하의 컬렉션 등 기타 그렇지 않으면 내가 바인딩 ItemsControls 바인딩에 대해 뭔가를 제안하거나 XAML에 대한 일반적인 책, 아담 네이선의 WPF Unleashed처럼 제안했다. m_vehicles를 다음 문장에서 새로운 것으로 바꾸기 위해 설정하는 것 같습니다. 또한 StackPanel의 DataContext는 목록에 허용되는 설정이지만 작동하지 않습니다. StackPanel 요소의 DataContext는 항목이 아닌 전체 목록이 될 것이므로 가져 오는 항목이됩니다. ItemsControl을 사용합니다.

+0

답변 해 주셔서 감사합니다. 실제로 작동하도록했습니다. 나중에 내가 한 일을 게시 할 것입니다. – webdad3