2016-06-22 50 views
0

用戶控件包含一些CustomControls與「國家」財產如何知道UserControl內的哪個元素改變了屬性?

<UserControl x:Class="MyNamespace.MyUserControl" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" 
     d:DesignHeight="133" d:DesignWidth="175" 
     x:Name="my_user_control">  
<Canvas> 
    <c:Led State="{Binding SegmentState, Mode=TwoWay}"/> 
    <c:Led State="{Binding SegmentState, Mode=TwoWay}"/> 
    <c:Led State="{Binding SegmentState, Mode=TwoWay}"/> 
</Canvas> 

SegmentState是一個依賴屬性與PropertyChangedCallback

public static DependencyProperty SegmentStateProperty = 
     DependencyProperty.Register("SegmentState", typeof(bool), typeof(MyUserControl), 
     new FrameworkPropertyMetadata(false, new PropertyChangedCallback(SegmentStateChanged))); 

但是這裏面SegmentStateChanged我找不到哪一個LED的更改的屬性。有什麼方法可以找到?

回答

0

如果SegmentState將是bool,你應該寫三篇SegmentState性能和每c:Led控制的State屬性綁定到一個不同:

<c:Led State="{Binding Segment0State, Mode=TwoWay}"/> 
<c:Led State="{Binding Segment1State, Mode=TwoWay}"/> 
<c:Led State="{Binding Segment2State, Mode=TwoWay}"/> 

如果段的數目是不固定的,你可以代替寫一個簡單的SegmentState類,它只有一個bool Value屬性,擁有一個名爲SegmentStates的實例集合,並綁定到該集合中的項目 - 但必須編寫一些代碼來響應Value屬性中的更改。上面的方法涉及到一點點'n'paste,但它是迄今爲止最容易正確工作的。

<ItemsControl ItemsSource="{Binding SegmentStates}> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <c:Led State="{Binding Value, Mode=TwoWay}"/> 
     <DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 
相關問題