2010-07-23 147 views
1

試圖理解WPF的綁定過程。WPF簡單綁定問題

請參閱底部的代碼。

在我的「viewmodel」中,查看底部的代碼,我有一個可觀察的集合,它是用項目填充listview的。那就是包含一個叫做symbol的路徑來設置組合框中所選索引的路徑。現在我的問題是,我需要從其他列表中填充組合框,然後再添加到列表視圖(一些默認值)。 因爲我剛剛開始使用WPF,我認爲也許你可以在同一個類中使用2個不同的ObservableCollections來實現這一目標,但這並沒有奏效。那麼我怎麼能填充數據模板的默認值之前,他們被綁定/添加到列表視圖?

這是我用來填充列表視圖,請參閱底部的viewmodelcontacts。

我也嘗試添加另一個類,我可以在我的組合框中使用一個新的observablecollection,但我沒有得到那個工作。 應該填充的數據來自位於我應用程序資源中的XML文件。

另一個問題,是否可以添加命令圖像?或者命令只能從繼承自button_base類的控件中獲得?我想在元素旁邊使用圖片,當用戶點擊該圖片時,他們會刪除該元素。

  • 從下面的答案,是有可能不添加按鈕,因爲我不想按鈕感覺嗎(比如懸停和點擊時)*

Window.xaml:

<r:RibbonWindow x:Class="Onyxia_KD.Windows.ContactWorkspace" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:r="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"   
    Title="Contact card" ResizeMode="NoResize" Height="600" Width="600" 
    Background="White"> 
<r:RibbonWindow.Resources> 
    <DataTemplate x:Key="cardDetailFieldTemplate"> 
     <TextBox Text="{Binding Path=Field}" MinWidth="150"></TextBox> 
    </DataTemplate> 
    <DataTemplate x:Key="cardDetailValueTemplate"> 
     <TextBox Text="{Binding Path=Value}" MinWidth="150"></TextBox> 
    </DataTemplate> 
    <DataTemplate x:Key="cardDetailSymbolTemplate"> 
     <!-- Here is the problem. Populating this with some default values for each entry before the selectedIndex is bound from the datasource --> 
     <ComboBox SelectedIndex="{Binding Path=Symbol}" DataContext="_vmSettings" ItemsSource="{Binding Symbols}" Grid.Column="1" Margin="0,0,10,0" VerticalAlignment="Center" HorizontalAlignment="Center"> 
      <ListViewItem Padding="0,3,0,3" Content="{Binding Path=Value}" />          
     </ComboBox> 
    </DataTemplate> 
    <DataTemplate x:Key="cardDetailCategoryTemplate"> 
     <ComboBox SelectedIndex="{Binding Path=Category}" Grid.Column="1" Margin="0,0,10,0" VerticalAlignment="Center" HorizontalAlignment="Center"> 
      <!--same as the combobox above but categories instead of symbols-->     
     </ComboBox> 
    </DataTemplate> 
</r:RibbonWindow.Resources> 
... 
<ListView ItemsSource="{Binding ContactData}" Foreground="Black" SelectionMode="Single" x:Name="cardDetailList" KeyDown="cardDetailList_KeyDown"> 
        <ListView.View> 
         <GridView> 
          <GridViewColumn Header="Category" Width="auto" CellTemplate="{StaticResource cardDetailCategoryTemplate}"></GridViewColumn> 
          <GridViewColumn Header="Field" Width="auto" CellTemplate="{StaticResource cardDetailFieldTemplate}"></GridViewColumn> 
          <GridViewColumn Header="Symbol" Width="70" CellTemplate="{StaticResource cardDetailSymbolTemplate}"></GridViewColumn> 
          <GridViewColumn Header="Value" Width="auto" CellTemplate="{StaticResource cardDetailValueTemplate}"></GridViewColumn>         
         </GridView> 
        </ListView.View>       
       </ListView> 

後面的代碼:

private ViewModelContacts _vm; 

    public ContactWorkspace() 
    { 
     InitializeComponent(); 

     _vm = new ViewModelContacts();    
     this.DataContext = _vm; 

    } 

    private void Run_MouseUp(object sender, MouseButtonEventArgs e) 
    { 
     _vm.AddNewDetail(); 
    } 

    private void Image_MouseUp(object sender, MouseButtonEventArgs e) 
    { 
     _vm.AddNewDetail(); 
    } 

    private void cardDetailList_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.Delete) 
     { 
      if (MessageBox.Show("Are you sure that you want to delete this?", "Warning!", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) 
      { 
       _vm.RemoveDetail(cardDetailList.SelectedIndex); 
      } 
     } 
    } 

ViewModelContacts:

public ObservableCollection<ContactCardData> ContactData { get; set; }    

    public ViewModelContacts() 
    { 

     ContactData = new ObservableCollection<ContactCardData>();    
     Populate(); 
    } 

    private void Populate() 
    { 
     ContactData.Add(new ContactCardData("Test", 0, 0, "Value123")); 
     ContactData.Add(new ContactCardData("Test2", 1, 1, "Value1234")); 
     ContactData.Add(new ContactCardData("Test3", 2, 2, "Value1235")); 
     ContactData.Add(new ContactCardData("Test4", 3, 3, "Value12356"));    
    } 

    public void UpdateNode() 
    { 
     ContactData.ElementAt(0).Value = "Giraff"; 
    } 

    public void AddNewDetail() 
    { 
     ContactData.Add(new ContactCardData()); 
    } 

    public void RemoveDetail(int position) 
    { 
     ContactData.RemoveAt(position); 
    } 

ViewModelContactData:

public class ContactCardData : DependencyObject 
{ 
    public int Category 
    { 
     get { return (int)GetValue(CategoryProperty); } 
     set { SetValue(CategoryProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for Category. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty CategoryProperty = 
     DependencyProperty.Register("Category", typeof(int), typeof(ContactCardData), new UIPropertyMetadata(0)); 

    public string Field 
    { 
     get { return (string)GetValue(FieldProperty); } 
     set { SetValue(FieldProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for Field. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty FieldProperty = 
     DependencyProperty.Register("Field", typeof(string), typeof(ContactCardData), new UIPropertyMetadata("")); 

    public string Value 
    { 
     get { return (string)GetValue(ValueProperty); } 
     set { SetValue(ValueProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty ValueProperty = 
     DependencyProperty.Register("Value", typeof(string), typeof(ContactCardData), new UIPropertyMetadata("")); 

    public int Symbol 
    { 
     get { return (int)GetValue(SymbolProperty); } 
     set { SetValue(SymbolProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for Symbol. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty SymbolProperty = 
     DependencyProperty.Register("Symbol", typeof(int), typeof(ContactCardData), new UIPropertyMetadata(0)); 

    public ContactCardData() 
    { 
    } 

    public ContactCardData(string field, int category, int symbol, string value) 
    { 
     this.Symbol = symbol; 
     this.Category = category; 
     this.Field = field; 
     this.Value = value; 
    } 
} 

回答

4

定義你的窗口類,如下所示(說明會後):

<Window x:Class="TestCustomTab.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:TestCustomTab="clr-namespace:TestCustomTab" Title="Window1" Height="300" Width="300"> 
     <Window.Resources> 
      <DataTemplate x:Key="workingTemplate"> 
       <Grid> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition Width="Auto"/> 
         <ColumnDefinition Width="*"/> 
        </Grid.ColumnDefinitions> 
        <TextBlock Grid.Column="0" Text="{Binding Name}"/> 
        <ComboBox Grid.Column="1" SelectedIndex="0" ItemsSource="{Binding Symbols}"> 
         <ComboBox.ItemTemplate> 
          <DataTemplate> 
           <Grid> 
            <Grid.ColumnDefinitions> 
             <ColumnDefinition Width="Auto"/> 
             <ColumnDefinition Width="*"/> 
            </Grid.ColumnDefinitions> 
            <Ellipse Grid.Column="0" Fill="Red" Height="5" Width="5"/> 
            <TextBlock Grid.Column="1" Text="{Binding}" /> 
           </Grid> 
          </DataTemplate> 
         </ComboBox.ItemTemplate> 
        </ComboBox> 
       </Grid> 
      </DataTemplate> 

      <DataTemplate x:Key="personalTemplate"> 
       <Grid> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition Width="Auto"/> 
         <ColumnDefinition Width="*"/> 
        </Grid.ColumnDefinitions> 
        <TextBlock Grid.Column="0" Text="{Binding Name}"/> 
        <ComboBox Grid.Column="1" SelectedIndex="0" ItemsSource="{Binding Symbols}"> 
         <ComboBox.ItemTemplate> 
          <DataTemplate> 
           <Grid> 
            <Grid.ColumnDefinitions> 
             <ColumnDefinition Width="Auto"/> 
             <ColumnDefinition Width="*"/> 
            </Grid.ColumnDefinitions> 
            <Ellipse Grid.Column="0" Fill="Green" Height="5" Width="5"/> 
            <TextBlock Grid.Column="1" Text="{Binding}" /> 
           </Grid> 
          </DataTemplate> 
         </ComboBox.ItemTemplate> 
        </ComboBox> 
       </Grid> 
      </DataTemplate> 

      <TestCustomTab:ContactDataByTypeTemplateSelector x:Key="contactDataByTypeTemplateSelector"/> 
     </Window.Resources> 
     <Grid x:Name="grid">   
      <ListView ItemsSource="{Binding ContactDataCollection, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TestCustomTab:Window1}}}"> 
       <ListView.View> 
        <GridView> 
         <GridViewColumn Header="Column" Width="200" CellTemplateSelector="{StaticResource contactDataByTypeTemplateSelector}"> 

         </GridViewColumn> 
        </GridView> 
       </ListView.View> 
      </ListView> 
     </Grid> 
    </Window> 

讓我們假設你的聯絡資料如下所示:

public class ContactData : INotifyPropertyChanged 
    { 
     private string _name; 
     private int _homePhone; 
     private int _mobilePhone; 
     private string _value; 
     private ContactDataType _dataType; 

     public ContactData() 
     { 
     } 

     public ContactData(string name, int homePhone, int mobilePhone, string value, ContactDataType dataType) 
     { 
      _name = name; 
      _dataType = dataType; 
      _value = value; 
      _mobilePhone = mobilePhone; 
      _homePhone = homePhone; 
     } 

     #region Implementation of INotifyPropertyChanged 

     public ContactDataType DataType 
     { 
      get { return _dataType; } 
      set 
      { 
       if (_dataType == value) return; 
       _dataType = value; 
       raiseOnPropertyChanged("DataType"); 
      } 
     } 

     public string Name 
     { 
      get { return _name; } 
      set 
      { 
       if (_name == value) return; 
       _name = value; 
       raiseOnPropertyChanged("Name"); 
      } 
     } 

     public int HomePhone 
     { 
      get { return _homePhone; } 
      set 
      { 
       if (_homePhone == value) return; 
       _homePhone = value; 
       raiseOnPropertyChanged("HomePhone"); 
      } 
     } 

     public int MobilePhone 
     { 
      get { return _mobilePhone; } 
      set 
      { 
       if (_mobilePhone == value) return; 
       _mobilePhone = value; 
       raiseOnPropertyChanged("MobilePhone"); 
      } 
     } 

     public string Value 
     { 
      get { return _value; } 
      set 
      { 
       if (_value == value) return; 
       _value = value; 
       raiseOnPropertyChanged("Value"); 
       raiseOnPropertyChanged("Symbols"); 
      } 
     } 

     public ReadOnlyCollection<char> Symbols 
     { 
      get 
      { 
       return !string.IsNullOrEmpty(_value) ? new ReadOnlyCollection<char>(_value.ToCharArray()) : new ReadOnlyCollection<char>(new List<char>()); 
      } 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 

     private void raiseOnPropertyChanged(string propertyName) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 

     #endregion 
    } 

它有型ContactDataType的數據類型屬性是枚舉:

public enum ContactDataType 
    { 
     Working, 
     Personal 
    } 

能否擁有不同的DataTemplates對於通過某些功能區分的相同實體,您需要使用DataTemplateSelector。該技術是從DataTemplateSelector繼承並覆蓋SelectTemplate方法。在我們的例子:

public class ContactDataByTypeTemplateSelector : DataTemplateSelector 
    { 
     public override DataTemplate SelectTemplate(object item, DependencyObject container) 
     { 
      var contactData = item as ContactData; 
      var control = container as FrameworkElement; 
      if (contactData != null & control != null) 
       switch (contactData.DataType) 
       { 
        case ContactDataType.Working: 
         return control.TryFindResource("workingTemplate") as DataTemplate; 
        case ContactDataType.Personal: 
         return control.TryFindResource("personalTemplate") as DataTemplate; 
        default: 
         return base.SelectTemplate(item, container); 
       } 

      return base.SelectTemplate(item, container); 
     } 
    } 

這裏是窗口1類在後面的代碼:

public partial class Window1 : Window 
    { 
     private ObservableCollection<ContactData> _contactDataCollection = new ObservableCollection<ContactData>(); 

     public Window1() 
     { 
      ContactDataCollection.Add(new ContactData("test1", 0, 1, "value1", ContactDataType.Working)); 
      ContactDataCollection.Add(new ContactData("test2", 0, 1, "value2", ContactDataType.Working)); 
      ContactDataCollection.Add(new ContactData("test3", 0, 1, "value3", ContactDataType.Working)); 
      ContactDataCollection.Add(new ContactData("test4", 0, 1, "value4", ContactDataType.Personal)); 
      ContactDataCollection.Add(new ContactData("test5", 0, 1, "value5", ContactDataType.Personal)); 

      InitializeComponent(); 

     } 


     public ObservableCollection<ContactData> ContactDataCollection 
     { 
      get { return _contactDataCollection; } 
     } 
    } 

現在解釋:

  1. 我們創造了一些類,我們需要代表用戶(ContactData)並讓他有功能 - ContactDataType

  2. 我們創建了資源2周的DataTemplates(x:Key很重要)用於ContactDataType.WorkingContactDataType.Personal

  3. 我們創造DataTemplateSelector的特徵是具有能力的交換機的模板。

  4. 在我們的第一個GridViewColumn中,我們定義了CellTemplateSelector並將其綁定到我們的ContactDataByTypeTemplateSelector

  5. 在運行時,只要集合發生變化ContactDataByTypeTemplateSelector根據項目特徵選擇我們模板,我們可以爲任意數量的已定義特徵提供任意數量的模板。

注意:更改TestCustomTab爲您的命名空間。

+0

嗨,謝謝你的迴應。我似乎沒有100%地解釋我自己。 我添加了我的XAML的listview和我的代碼,我沒有設法工作的是符號。我不知道該綁定什麼。我想將所有預定義的xml內容添加到外部類,並將其用於所有預定義的數據綁定。但我怎樣才能將一個組合框綁定到2個datacontexts在同一時間?一個用於應用當前選定的索引,另一個用於在用默認值顯示組合框之前填​​充組合框。 – Patrick 2010-07-24 08:25:16

1

對於最後一個問題,你可以使用一個按鈕,模板它包括圖像。