如何在Silverlight中从DataTemplate绑定到ItemsControl中的索引

时间:2014-10-27 08:10:08

标签: c# silverlight

我有一个使用ItemsControl的Silverlight应用程序。在ItemsControl里面,我有一个DataTemplate,其定义如下:

XAML

<ItemsControl Grid.Row="1" Grid.ColumnSpan="5" x:Name="dgOdds">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Grid x:Name="gRoot">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="200"/>
                                <ColumnDefinition Width="200"/>
                                <ColumnDefinition Width="200"/>
                            </Grid.ColumnDefinitions>

                            <TextBox x:Name="OF1" Grid.Column="0" Text="{Binding OddFactor, Mode=TwoWay}" FontWeight="Bold" VerticalAlignment="Center" HorizontalContentAlignment="Center"/>
                            <TextBox x:Name="OFX" Grid.Column="1" Text="{Binding OddFactor, Mode=TwoWay}" FontWeight="Bold" VerticalAlignment="Center" HorizontalContentAlignment="Center"/>
                            <TextBox x:Name="OF2" Grid.Column="2" Text="{Binding OddFactor, Mode=TwoWay}" FontWeight="Bold" VerticalAlignment="Center" HorizontalContentAlignment="Center"/>
                        </Grid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

我有一个对象列表:

C#

ObservableCollection<TestObj> SomeList = new ObservableCollection<TestObj>;
SomeList.Add(new TestObj(){ OddType = 1, OddFakctor = 1.1 });
SomeList.Add(new TestObj(){ OddType = 2, OddFakctor = 2.2 });
SomeList.Add(new TestObj(){ OddType = 3, OddFakctor = 3.3 });
this.dgOdds.ItemsSource = this.Collection;

TestObj类如下:

public class TestObj
    {
        public double OddType { get; set;}
        public double OddFakctor { get; set; }
    }

我想在控件中显示类似的属性:

If OddType equal 1, than show in TextBox x:Name="OF1", 
if OddType equal 2, than show in TextBox x:Name="OFX", 
if OddType equal 3, than show in TextBox x:Name="OF3"

怎么做?

1 个答案:

答案 0 :(得分:0)

因为你想要显示OddType等于1或2或3,你只能有一个文本块。 如果选择1,则其中一个TextBox将具有OF1,而其他Text将为null。

private double _oddfactor;
public double OddFakctor 
 {
        get
        {
            return _oddfactor;
        }
        set
        {
            _oddfactor = value;
            OnPropertyChanged(() => OddFakctor);
        }
    }

如果你在这里更新_OddFakctor,它会将文本框绑定值传递给_oddfactor