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

本文关键字:ItemsControl 索引 绑定 DataTemplate silverlight 中的 | 更新日期: 2023-09-27 18:28:00

我有一个Silverlight应用程序正在使用ItemsControl。在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"

如何做到这一点?

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

由于您希望显示OddType等于1、2或3,因此您只能有一个文本块。如果选择了1,那么其中一个TextBox将具有OF1,而其他将为空。

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

如果在这里更新_oddfactor,它将用传递给该_oddfactor 的值wat u r绑定文本框