【问题标题】:How can I set ComboboxItem isEnable property with binding?如何使用绑定设置 Combobox Item isEnabled 属性?
【发布时间】:2022-01-03 12:34:35
【问题描述】:

我有一个模型视图和一个名为 isEnable 的属性,我想设置 comboboxItem IsEnable 属性并绑定到模型视图中创建的属性,问题是我在组合框中创建了数据模板,所以这不是一个简单的组合框,这是我的代码:

<ComboBox x:Name="ComboBoxUsers" ItemsSource="{Binding Users}" FontFamily="Arial" FontSize="11" Grid.Row="3" Height="30"  Margin="10,5,5,5">
<ComboBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal" >
            <Image />
            <TextBlock />
        </StackPanel>
        <DataTemplate.Resources>
            <Style TargetType="ComboBoxItem">
                <Setter Property="IsEnable" Value="{Binding IsEnable}"/>
            </Style>
        </DataTemplate.Resources>
    </DataTemplate>
</ComboBox.ItemTemplate>

简单的用户类:

public class Users 
{

    public string Name { get; set; }

    public bool IsEnable { get; set; }

    public Users()
    {

    }
}

我怎样才能做到这一点?

【问题讨论】:

  • 我已经有一段时间没有用 WPF 做任何事情了,但我很确定你不能只将你的 ItemsSource 绑定到一个类,而是你必须将它绑定到一个属性,并且该属性必须是某种列表或集合,然后绑定到该集合的类的属性,例如{Binding Path=IsEnable}
  • 是的,我做了这个,它是一个集合(列表)

标签: c# wpf xaml


【解决方案1】:

我通过添加此代码解决了我的问题:

 <ComboBox.ItemContainerStyle>
     <Style TargetType="ComboBoxItem"
        <Setter Property="IsEnable" Value="{Binding IsEnable}" />
     </Style>
 </ComboBox.ItemContainerStyle>

所以完整的代码是:

<ComboBox x:Name="ComboBoxUsers" ItemsSource="{Binding Users}" FontFamily="Arial" FontSize="11" Grid.Row="3" Height="30"  Margin="10,5,5,5">
<ComboBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal" >
            <Image />
            <TextBlock />
        </StackPanel>
         <ComboBox.ItemContainerStyle>
            <Style TargetType="ComboBoxItem" >
                <Setter Property="IsEnable" Value="{Binding IsEnable}" />
            </Style>
         </ComboBox.ItemContainerStyle>
    </DataTemplate>
</ComboBox.ItemTemplate>

【讨论】:

  • 该类未实现INotifyPropertyChanged,因此任何属性更改都不会反映在 UI 上。如果你这样离开,你可能需要将绑定模式更改为OneTime,以避免内存泄漏。
  • 你能告诉我更多关于OneTime模式的信息吗(提供更多细节)?
  • 做一些研究,网上有很多资源会比我解释得更好。看到这个:docs.microsoft.com/en-us/dotnet/api/… 和这个:stackoverflow.com/questions/18542940/…
猜你喜欢
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多