2015-08-25 21 views
1

如果將UpdateSourceTrigger設置爲PropertyChanged,則會運行以下代碼,但在UpdateSourceTrigger設置爲LostFocus時會在初始化時引發異常。將UpdateSourceTrigger設置爲LostFocus時的異常

這個實現有什麼問題,它如何被糾正?

異常

"'ComboBoxSample.ComboBoxBehavior' type must derive from FrameworkElement or FrameworkContentElement." 

查看

<Window.DataContext> 
    <local:ViewModel/> 
</Window.DataContext> 

<Grid> 
    <ComboBox ItemsSource="{Binding Path=Apples}" 
       DisplayMemberPath="Cultivar"> 
     <i:Interaction.Behaviors> 
      <local:ComboBoxBehavior 
       SelectedValue="{Binding Path=SelectedId, 
             Mode=TwoWay, 
             UpdateSourceTrigger=LostFocus}"/> 
     </i:Interaction.Behaviors> 
    </ComboBox> 
</Grid> 

行爲

public class ComboBoxBehavior : Behavior<ComboBox> 
{ 
    public static readonly DependencyProperty SelectedValueProperty 
     = DependencyProperty.Register("SelectedValue", 
             typeof(object), 
             typeof(ComboBoxBehavior), 
             new FrameworkPropertyMetadata(null, (target, args) => { })); 

    public object SelectedValue 
    { 
     get { return GetValue(SelectedValueProperty); } 
     set { SetValue(SelectedValueProperty, value); } 
    } 

    protected override void OnAttached() { base.OnAttached(); } 

    protected override void OnDetaching() { base.OnDetaching(); } 
} 

視圖模型

public class ViewModel 
{ 
    public ObservableCollection<Apple> Apples { get; set; } 

    public int SelectedId { get; set; } 

    public ViewModel() 
    { 
     Apples = new ObservableCollection<Apple> 
     { 
      new Apple() 
      { 
       Id = 0, 
       Cultivar = "Alice", 
       Weight = 0.250 
      }, 
      new Apple() 
      { 
       Id = 1, 
       Cultivar = "Golden", 
       Weight = 0.3 
      }, 
      new Apple() 
      { 
       Id = 2, 
       Cultivar = "Granny Smith", 
       Weight = 0.275 
      } 
     }; 
    } 
} 

public class Apple 
{ 
    public int Id { get; set; } 

    public string Cultivar { get; set; } 

    public double Weight { get; set; } 
} 

回答

0

您的問題是你想用你的<local:ComboBoxBehavior />,如果它是一個塊(骨架元素)。在xaml中,只能編寫從Framework元素繼承的塊(如段落,TextBlock等)。由於我不確定你想要達到的目標,所以這幾乎是我可以給你的詳細程度的最佳答案。

+0

我的目標是弄清楚爲什麼在描述的情況下設置一個UpdateSourceTrigger綁定到一個依賴項屬性爲LostFocus會引發異常,同時將觸發器設置爲PropertyChanged可以正常工作。請注意,上面的代碼只是演示了這種行爲。 – Ilya

0

我在這個自己很新,所以不知道它會有多大的幫助。首先,你是否試圖將SelectedItem和SelectedValue一起更新?如果是這樣,也許不需要行爲(警告,未經測試的代碼!):

<Window.DataContext> 
    <local:ViewModel/> 
</Window.DataContext> 

<Grid> 
    <ComboBox ItemsSource="{Binding Path=Apples}" 
      DisplayMemberPath="Cultivar" SelectedValue="{Binding Path=SelectedId, 
            Mode=TwoWay, 
            UpdateSourceTrigger=LostFocus}" > 
    </ComboBox> 
</Grid> 

或者類似的東西組合框的的SelectedValue直接綁定到SelectedId在視圖模型。然後,如果您需要在更改SelectedValue時的行爲中執行某些操作,請將其作爲獨立於SelectedId更新的自己的行爲進行創建。這些幫助有用?

+0

感謝您的評論。我正在處理的實際情況更加複雜,這種複雜性在這裏沒有附加價值。這個問題可以歸結爲上面描述的情況,只要綁定到依賴項屬性的UpdateSourceTrigger沒有設置爲LostFocus,一切工作都正常。當設置爲LostFocus時,相應的視圖在初始化時會引發異常。 – Ilya

相關問題