Windows 10 UWP App中的可编辑网格

时间:2016-01-26 19:52:40

标签: c# .net xaml windows-10 uwp

我使用下面的listview创建产品界面,如何在此视图中使所选项目可编辑。我想将所选行的每个单元格放在TextBox而不是TextBlock中,以便用户可以编辑这些值。寻求社区的帮助。

<Grid>
    <StackPanel>
        <ListView Name="ItemsList" ItemsSource="{x:Bind products}">
         <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                    <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" />
                </Style>
            </ListView.ItemContainerStyle>

        <ListView.ItemTemplate>
            <DataTemplate x:DataType="data:Product">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Grid.Resources>
                        <Style TargetType="TextBlock">
                            <Setter Property="Margin" Value="5,0" />
                        </Style>
                    </Grid.Resources>
                    <TextBlock Grid.Column="0" Text="{x:Bind ProductId}" />
                    <TextBlock Grid.Column="1" Text="{x:Bind ProductName}" />                        
                    </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    </StackPanel>
</Grid>

1 个答案:

答案 0 :(得分:1)

@ Jackie建议一直使用TextBox,在未选择项目时将其设为只读,这是一个很好的建议;它简化了逻辑和布局。 (在可见TextBox和可见TextBlock之间切换非常棘手,因为您希望文本位于完全相同的位置。)

为了便于说明,我将使用这个简化的模型对象:

public sealed class Item : INotifyPropertyChanged
{
    private bool isReadOnly = true;

    public bool IsReadOnly
    {
        get
        {
            return isReadOnly;
        }

        set
        {
            isReadOnly = value;
            OnPropertyChanged();
        }
    }

    public string Value { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

接下来是ListView

<ListView SelectionChanged="OnSelectionChanged">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBox
                Text="{Binding Value}"
                IsReadOnly="{Binding IsReadOnly}" />
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.Items>
        <local:Item Value="One" />
        <local:Item Value="Two" />
        <local:Item Value="Three" />
        <local:Item Value="Four" />
    </ListView.Items>
</ListView>

最后,代码隐藏,切换IsReadOnly的{​​{1}}属性:

Item
相关问题