如何绑定类的属性的属性?

时间:2014-01-02 16:44:40

标签: c# windows-phone-7 binding

我有以下课程:

public class Car
{
    [DataMember(Name = "versionID")]
    public string Id { get; set; }

    [DataMember(Name = "state")]
    public State State { get; set; }

    [DataMember(Name = "type")]
    public string Type { get; set; } 
}


public class State
{
    public string ID { get; set; }
    [DataMember(Name = "on")]
    public bool StateOn{ get; set; }

    [DataMember(Name = "description ")]
    public int Description { get; set; }

}

我有一个ObservableCollection,我将它作为ItemsSource绑定到Listbox。

ListboxItemTemplate:

<Grid>
    <TextBlock Text="{Binding ID}" />
    <TextBlock Text="{Binding Type}" />
   <ToggleButton Tag="{Binding Description}" IsChecked="{Binding StateOn}"/>

       

如何将StateOn状态的bool绑定到ItemTemplate中ToggleButton的IsChecked?

亲切的问候, 尼尔斯

2 个答案:

答案 0 :(得分:1)

你应该能够像这样引用它们......

<Grid>
    <TextBlock Text="{Binding ID}" />
    <TextBlock Text="{Binding Type}" />
   <ToggleButton Tag="{Binding State.Description}" IsChecked="{Binding State.StateOn}"/>

答案 1 :(得分:1)

我确信有更简洁的方法可以做到这一点,但你可以尝试在每个控件中设置DataContext,但在我看来它有点难看:

<Grid>
    <TextBlock Text="{Binding ID}">
        <TextBlock.DataContext>
             <local:Car/>
         </TextBlock.DataContext>
    </TextBlock>
    <TextBlock Text="{Binding Type}">
        <TextBlock.DataContext>
            <local:Car/>
        </TextBlock.DataContext>
    </TextBlock>
    <ToggleButton Tag="{Binding Description}" Content="{Binding StateOn}"
                  IsChecked="{Binding StateOn, Mode=TwoWay}">
        <ToggleButton.DataContext>
            <local:State/>
        </ToggleButton.DataContext>
    </ToggleButton>
</Grid>

在您的代码隐藏中:

public class State : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public string ID { get; set; }
    public int Description { get; set; }

    private bool stateOn { get; set; }
    public bool StateOn
    {
        get 
        {
            return stateOn;
        }

        set
        {
            stateOn = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("StateOn"));
            }
        }
    }
}

顺便说一句,我现在删除了属性,所以它不会太分散注意力。我还在ToggleButton中添加了文本内容,仅用于故障排除。如果您不希望在用户单击切换按钮时更改StateOn bool,则可以将Mode更改为OneWay。有关Mode的更多信息,请访问:http://msdn.microsoft.com/en-us/library/system.windows.data.binding.mode(v=vs.110).aspx