猿问

我可以在 xaml 代码中禁用 WPF 组合框的第一项吗?

考虑以下组合框:


<ComboBox ItemsSource="{Binding Presets.VolumePresetList}" SelectedIndex="{Binding VolumePresetSelectedIndex, UpdateSourceTrigger=PropertyChanged}" Margin="10, 10" HorizontalAlignment="Left"

            MinWidth="150">

    <ComboBox.ItemTemplate>

        <DataTemplate>

            <TextBox Text="{Binding PresetName, UpdateSourceTrigger=Explicit}" VerticalAlignment="Center" Height="20" BorderThickness="0" LostFocus="TextBox_LostFocus" KeyUp="TextBox_KeyUp"/>

        </DataTemplate>

    </ComboBox.ItemTemplate>

</ComboBox>

组合框的第一个项目是默认预设,在文本框中具有相应的默认名称。因此,用户不应该能够对第一项进行输入 - 因此我想禁用第一项的文本框。


我知道我可以在包含类或视图模型的构造函数中运行一个函数,它会禁用第一个索引上的文本框,但是我想知道这是否可以直接在 xaml 代码中实现(我会发现它更优雅做这种静态事情的方式)。


胡子哥哥
浏览 67回答 2
2回答

慕的地10843

您可以利用PreviousData RelativeSource 将为null集合的第一个元素返回这一事实。知道您可以将DataTrigger添加到 DataTemplate 以将其IsEnabled属性设置TextBox为 false。这是ItemTemplate带有PreviousData绑定的简化版本:&nbsp; &nbsp; &nbsp; &nbsp;<ComboBox.ItemTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <DataTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <TextBox x:Name="TextBox" />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <DataTemplate.Triggers>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=PreviousData}}"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Value="{x:Null}">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Setter TargetName="TextBox" Property="IsEnabled" Value="False" />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </DataTrigger>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </DataTemplate.Triggers>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </DataTemplate>&nbsp; &nbsp; &nbsp; &nbsp; </ComboBox.ItemTemplate>

www说

我用DataBindingfor创建了一个复合集合,ListView但逻辑是一样的:<ListView SelectedValue="{Binding youVMPropertyHere}">&nbsp; &nbsp; <ListView.ItemsSource>&nbsp; &nbsp; &nbsp; &nbsp; <CompositeCollection>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ListViewItem IsHitTestVisible="False">Default Item</ListViewItem>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <CollectionContainer Collection="{Binding Source={StaticResource cvsPresetLists}}"/>&nbsp; &nbsp; &nbsp; &nbsp; </CompositeCollection>&nbsp; &nbsp; </ListView.ItemsSource><!-- Where--><Window.Resources>&nbsp; &nbsp; <CollectionViewSource Source="{Binding Presets.VolumePresetList}" x:Key="cvsPresetLists"/></Window.Resources>&nbsp;&nbsp;这样你就可以让第一个项目不可选。我也会使用SelectedValue而不是SelectedIndex.
随时随地看视频慕课网APP
我要回答