wpf 相关问题

Windows Presentation Foundation或WPF是用于在基于Windows的应用程序中呈现用户界面的子系统。

wpf 菜单项的键盘快捷键

我正在尝试使用以下命令向 xaml 代码中的菜单项添加键盘快捷键 使用 Ctrl+O 但是...

回答 3 投票 0

将Cell中具有CustomClass的DataTable绑定到DataGrid WPF

我有数据网格。 我有数据网格。 <DataGrid ItemsSource="{Binding DataView}" x:Name="AttributeGrid" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" EnableColumnVirtualization="False" EnableRowVirtualization="False" DataContextChanged="AttributeGrid_DataContextChanged"> </DataGrid> 对于该 DataGrid 的单元格,我有自定义样式 <Style x:Key="DataGridDataViewCustomCellStyle" TargetType="{x:Type DataGridCell}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="DataGridCell"> <Grid> <ComboBox x:Name="ComboBoxCondition" IsEditable="True" ItemsSource="{Binding Values}" Visibility="Collapsed" SelectedValue="{Binding SelectedValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="ValueID" DisplayMemberPath="ValueStr"/> <TextBox x:Name="TextBoxCondition" Text="{Binding TextValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="True" Visibility="Collapsed"/> <DatePicker x:Name="DateCondition" Text="{Binding DateValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="True" Visibility="Collapsed"/> </Grid> <ControlTemplate.Triggers> <DataTrigger Binding="{Binding ValueType}" Value="Text"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Visible"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Hidden"/> </DataTrigger> <DataTrigger Binding="{Binding ValueType}" Value="Combobox"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Visible"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Hidden"/> </DataTrigger> <DataTrigger Binding="{Binding ValueType}" Value="Date"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Visible"/> </DataTrigger> <DataTrigger Binding="{Binding IsModified, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="True"> <Setter Property="Background" TargetName="TextBoxCondition" Value="Cornsilk"/> <Setter Property="Background" TargetName="ComboBoxCondition" Value="Cornsilk"/> <Setter Property="Background" TargetName="DateCondition" Value="Cornsilk"/> </DataTrigger> <DataTrigger Binding="{Binding IsModified, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="False"> <Setter Property="Background" TargetName="TextBoxCondition" Value="White"/> <Setter Property="Background" TargetName="ComboBoxCondition" Value="White"/> <Setter Property="Background" TargetName="DateCondition" Value="White"/> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> 如果 DataView 基于 List<object> gridAttributes = new List<AttributeItem>(); gridAttributes add some data ..... DataView = CollectionViewSource.GetDefaultView(gridAttributes); 一切都按预期进行。在 DataGridCell 中,我有 AttributeIem 对象,并且可以根据需要设置其样式。 但是,当 DataView 基于 DataTable 时,然后在 DataGridCell 中,由于某种原因我得到了 DataRowView,然后 Style 不起作用,一切都出错了。 RunDataTable.Rows.Clear(); RunDataTable.Columns.Clear(); RunDataTable.Columns.Add("SectionName"); RunDataTable.Columns.Add("RunName"); foreach (AttributeItem attr in gridAttributes) { RunDataTable.Columns.Add(attr.AttributeName, typeof(AttributeItem)); } DataRow row = RunDataTable.NewRow(); row["SectionName"] = section; row["RunName"] = name; foreach (AttributeItem item in gridAttributes) { row[item.AttributeName] = item; } RunDataTable.Rows.Add(row); DataView = new DataView(RunDataTable); 这是我收到的错误绑定列表 System.Windows.Data Error: 40 : BindingExpression path error: 'IsModified' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=IsModified; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'Values' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=Values; DataItem='DataRowView' (HashCode=47477033); target element is 'ComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable') System.Windows.Data Error: 40 : BindingExpression path error: 'SelectedValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=SelectedValue; DataItem='DataRowView' (HashCode=47477033); target element is 'ComboBox' (Name=''); target property is 'SelectedValue' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'TextValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=TextValue; DataItem='DataRowView' (HashCode=47477033); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') System.Windows.Data Error: 40 : BindingExpression path error: 'DateValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=DateValue; DataItem='DataRowView' (HashCode=47477033); target element is 'DatePicker' (Name=''); target property is 'Text' (type 'String') System.Windows.Data Error: 40 : BindingExpression path error: 'ValueType' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=ValueType; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'ValueType' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=ValueType; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'ValueType' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=ValueType; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'IsModified' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=IsModified; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'IsModified' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=IsModified; DataItem='DataRowView' (HashCode=47477033); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'Values' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=Values; DataItem='DataRowView' (HashCode=47477033); target element is 'ComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable') System.Windows.Data Error: 40 : BindingExpression path error: 'SelectedValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=SelectedValue; DataItem='DataRowView' (HashCode=47477033); target element is 'ComboBox' (Name=''); target property is 'SelectedValue' (type 'Object') System.Windows.Data Error: 40 : BindingExpression path error: 'TextValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=TextValue; DataItem='DataRowView' (HashCode=47477033); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') System.Windows.Data Error: 40 : BindingExpression path error: 'DateValue' property not found on 'object' ''DataRowView' (HashCode=47477033)'. BindingExpression:Path=DateValue; DataItem='DataRowView' (HashCode=47477033); target element is 'DatePicker' (Name=''); target property is 'Text' (type 'String') 任何建议我如何调整我的样式或代码隐藏以使其正常工作。 谢谢。 我尝试了不同的数据源方式。但不幸的是每次我都会遇到同样的错误 添加列: public static void RefreshColumnsFromModel(this DataGrid datagrid, DataGridRuns gridModel) { var myResourceDictionary = new ResourceDictionary(); myResourceDictionary.Source = new Uri("/SomeSource;component/Resources/SomeSource.xaml", UriKind.RelativeOrAbsolute); datagrid.Columns.Clear(); foreach (ColumnWithFilter column in gridModel.Columns.OrderBy(c => c.Index)) { if (column.IsReadOnly) { datagrid.Columns.Add( new DataGridTextColumn() { Header = column.ColumnHeader, IsReadOnly = column.IsReadOnly, Binding = new Binding(column.ColumnBinding), CellStyle = myResourceDictionary["DataGridReadOnlyCellStyle"] as Style, HeaderTemplate = datagrid.Resources["HeaderTemplate"] as DataTemplate } ); } else { datagrid.Columns.Add( new DataGridTemplateColumn() { Header = column.ColumnHeader, IsReadOnly = column.IsReadOnly, //Binding = new Binding(column.ColumnBinding), //HeaderTemplate = myResourceDictionary["HeaderTemplate"] as DataTemplate HeaderTemplate = datagrid.Resources["HeaderTemplate"] as DataTemplate, CellStyle = myResourceDictionary["DataGridDataViewCustomCellStyle"] as Style } ); } } } DataGridRuns 代表 DataGrid 的模型,一些用于过滤和排序的自定义行为 public class DataGridRuns : BaseClass { private List<AttributeItem> gridAttributes = new List<AttributeItem>(); public ObservableCollection<AttributeItem> GridAttributes { get { return new ObservableCollection<AttributeItem>(gridAttributes); } set { gridAttributes = value.ToList(); RaisePropertyChanged(); } } public DataTable RunDataTable { get; set; } = new DataTable("RunData"); private DataView dataView = null; public DataView DataView { get { return dataView; } } private ColumnWithFilter selectedColumn = null; public ColumnWithFilter SelectedColumn { get { return selectedColumn; } set { selectedColumn = value; RaisePropertyChanged(); } } public Action RefreshColumns; private List<ColumnWithFilter> columns = new List<ColumnWithFilter>(); public ObservableCollection<ColumnWithFilter> Columns { get { return new ObservableCollection<ColumnWithFilter>(columns); } set { columns = value.ToList(); RaisePropertyChanged(); } } public DataGridRuns() { } private List<AttributeItem> CreateAttributesFromInfo(IList<AttributeInfo> _attributes) { List<AttributeItem> result = new List<AttributeItem>(); try { foreach (var attr in _attributes) { result.Add(new AttributeItem(attr)); } } catch (Exception ex) { } return result; } public void AddRun(string section, string name, IList<AttributeInfo> _attributes, bool template = false) { var attr = CreateAttributesFromInfo(_attributes); if (gridAttributes == null || gridAttributes.Count() == 0) { gridAttributes = new List<AttributeItem>(attr); CreateColumns(); } DataRow row = RunDataTable.NewRow(); row["SectionName"] = section; row["RunName"] = name; foreach (AttributeItem item in gridAttributes) { row[item.AttributeName] = item; } RunDataTable.Rows.Add(row); dataView = new DataView(RunDataTable); //dataView = CollectionViewSource.GetDefaultView(RunDataTable); } public void ClearData() { gridAttributes.Clear(); gridAttributes = new List<AttributeItem>(); } public void CreateColumns() { RunDataTable.Rows.Clear(); RunDataTable.Columns.Clear(); columns = new List<ColumnWithFilter>(); ColumnWithFilter col = null; col = new ColumnWithFilter("Section Name", nameof(AttributeItem.SectionName)) { Index = 0, IsReadOnly = true, }; columns.Add(col); RunDataTable.Columns.Add("SectionName"); col = new ColumnWithFilter("Run Name", nameof(AttributeItem.RunName)) { Index = 1, IsReadOnly = true, }; columns.Add(col); RunDataTable.Columns.Add("RunName"); int colIndex = 1; foreach (AttributeItem attr in gridAttributes) { col = new ColumnWithFilter(attr.AttributeName, nameof(attr)) { Index = ++colIndex, IsReadOnly = false, }; columns.Add(col); RunDataTable.Columns.Add(attr.AttributeName, typeof(AttributeItem)); } } public void RefreshDataView() { foreach (DataRow item in RunDataTable.Rows) { item.ItemArray.ToList().ForEach(a => (a as AttributeItem)?.StartMarkingModifications()); } RaisePropertyChanged(nameof(DataView)); } public void RefreshPopupContent(string header = "") { selectedColumn = columns.Where(c => c.ColumnHeader.Equals(header)).FirstOrDefault(); if (selectedColumn == null) return; selectedColumn.RefreshFilterValues(gridAttributes .Where(a => !string.IsNullOrEmpty((string)GetPropertyValue(a, selectedColumn.ColumnBinding))) .Select(a => (string)GetPropertyValue(a, selectedColumn.ColumnBinding)).Distinct().ToList()); RaisePropertyChanged(nameof(SelectedColumn)); } public void Filtering() { UpdateDataViewRowFilter(); } private void UpdateDataViewRowFilter() { string rowFilter = string.Empty; foreach (ColumnWithFilter column in columns.Where(c => c.FilterIndex > 0)) { string andStr = !string.IsNullOrEmpty(rowFilter) ? " AND " : ""; switch (column.FilterIndex) { case 1: rowFilter += andStr + $"{column.ColumnBinding} IS NULL"; break; default: rowFilter += andStr + $"{column.ColumnBinding} = '{column.FilteredValue}'"; //filterResult = ((string)GetPropertyValue(attribute, column.ColumnBinding)).Equals(column.FilteredValue); break; } } (dataView as DataView).RowFilter = rowFilter; } public object GetPropertyValue(object obj, string propertyName) { return obj.GetType().GetProperty(propertyName)?.GetValue(obj, null); } } 这是我在 DataTable 中看到的,我希望在 DataGrid 中也能看到同样的结果 DataTable Visualizer 的屏幕截图 添加这是我在 UI 中看到的 具有列过滤的自定义网格 我不确定我是否正确理解了您的所有代码。我会根据我能理解的提供一个解决方案。 在数据表单元格中,您的类型为“AttributeItem”。具有路径“column.ColumnBinding”的绑定将从相应的单元格返回该类型的实例。 ValueType 和 IsModified 属性(在 ControlTemplate 中使用)属于此实例。 在这种情况下,我认为您错误地使用了 DataGridCell 样式更改。相反,您需要为单元格的内容创建一个数据模板。 <DataTemplate x:Key="DataGridDataViewCustomCellDataTemplate"> <Grid> <ComboBox x:Name="ComboBoxCondition" IsEditable="True" ItemsSource="{Binding Values}" Visibility="Collapsed" SelectedValue="{Binding SelectedValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="ValueID" DisplayMemberPath="ValueStr"/> <TextBox x:Name="TextBoxCondition" Text="{Binding TextValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="True" Visibility="Collapsed"/> <DatePicker x:Name="DateCondition" Text="{Binding DateValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="True" Visibility="Collapsed"/> </Grid> <DataTemplate.Triggers> <DataTrigger Binding="{Binding ValueType}" Value="Text"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Visible"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Hidden"/> </DataTrigger> <DataTrigger Binding="{Binding ValueType}" Value="Combobox"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Visible"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Hidden"/> </DataTrigger> <DataTrigger Binding="{Binding ValueType}" Value="Date"> <Setter Property="Visibility" TargetName="TextBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="ComboBoxCondition" Value="Hidden"/> <Setter Property="Visibility" TargetName="DateCondition" Value="Visible"/> </DataTrigger> <DataTrigger Binding="{Binding IsModified, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="True"> <Setter Property="Background" TargetName="TextBoxCondition" Value="Cornsilk"/> <Setter Property="Background" TargetName="ComboBoxCondition" Value="Cornsilk"/> <Setter Property="Background" TargetName="DateCondition" Value="Cornsilk"/> </DataTrigger> <DataTrigger Binding="{Binding IsModified, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="False"> <Setter Property="Background" TargetName="TextBoxCondition" Value="White"/> <Setter Property="Background" TargetName="ComboBoxCondition" Value="White"/> <Setter Property="Background" TargetName="DateCondition" Value="White"/> </DataTrigger> </DataTemplate.Triggers> </DataTemplate> 在模板 DataGridTemplateColumn 中,您需要创建一个带有 ContentControl 的模板,该模板将接受 Content 属性中路径“column.ColumnBinding”的绑定以及上述 ContentTemplate 属性中的模板。 private const string templateString = @" <DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> <ContentControl Content=""{{Binding {0}}}"" ContentTemplate=""{{DynamicResource DataGridDataViewCustomCellDataTemplate}}""/> </DataTemplate> "; public static void RefreshColumnsFromModel(this DataGrid datagrid, DataGridRuns gridModel) { var myResourceDictionary = new ResourceDictionary(); myResourceDictionary.Source = new Uri("/SomeSource;component/Resources/SomeSource.xaml", UriKind.RelativeOrAbsolute); datagrid.Columns.Clear(); foreach (ColumnWithFilter column in gridModel.Columns.OrderBy(c => c.Index)) { if (column.IsReadOnly) { datagrid.Columns.Add( new DataGridTextColumn() { Header = column.ColumnHeader, IsReadOnly = column.IsReadOnly, Binding = new Binding(column.ColumnBinding), CellStyle = myResourceDictionary["DataGridReadOnlyCellStyle"] as Style, HeaderTemplate = datagrid.Resources["HeaderTemplate"] as DataTemplate } ); } else { string templateSource = string.Format(templateString, column.ColumnBinding); var template = XamlReader.Parse(templateSource); datagrid.Columns.Add( new DataGridTemplateColumn() { Header = column.ColumnHeader, IsReadOnly = column.IsReadOnly, //Binding = new Binding(column.ColumnBinding), //HeaderTemplate = myResourceDictionary["HeaderTemplate"] as DataTemplate HeaderTemplate = datagrid.Resources["HeaderTemplate"] as DataTemplate, CellStyle = myResourceDictionary["DataGridDataViewCustomCellStyle"] as Style } ); } } } 不幸的是,我无法测试这段代码。但如果您提供重现这些情况的最少代码,我可以进行测试并准备有保证的工作版本。

回答 1 投票 0

将 RotateTransform 应用于 Canvas 中的 WPF TextBlock 时,TranslateTransform 未“保留”

在画布中绘制一些 TextBlock 以及其他形状时,我使用 TranslateTransform 放置它们。 我没有在 XAML 中执行此操作,因为我将在运行时生成对象。 点原点,

回答 1 投票 0

将文本转换为图像?

如何将文本转换为图像?图像分辨率必须非常小,约为 30x30 到 100x100,并且只能是单色。 我尝试过使用 GDI 来执行此操作,但它会生成带有多个文本的文本...

回答 3 投票 0

将击键发送到 WPF 应用程序本身

在我的应用程序中,我正在捕获击键,当击键不是条形码的一部分时,我想将它们发送到应用程序。击键需要发送到应用程序本身。 我试过了

回答 1 投票 0

以编程方式在wpf中填充网格:自动行高似乎不起作用

我正在以编程方式用行填充 WPF 网格。每行都分配有一个用户控件。该用户控件本身包含一个网格,只有一行和三列。第三列可以包含 Te...

回答 4 投票 0

在文本编辑器框中选择特殊字符时,Avalon 文本编辑器会显示反斜杠(\) 或下划线(__)

在我的 WPF 应用程序中,我有多个接收 json 文本的 Avalon 文本框。对于语法突出显示,我使用官方 .xshd 文件(https://github.com/icsharpcode/AvalonEdit/blob/master/ICShar...

回答 1 投票 0

如何在 MVVM WPF 模式中执行关闭、隐藏窗口等命令或启动进程的命令

我正在 WPF 平台上使用 MVVM 模式开发应用程序,但我不知道如何使用与 ViewModel 中的视图直接相关的命令,这样就不会破坏

回答 1 投票 0

在 WPF .NET Core 8.0 类型的项目中使用使用 Store API 的 .NET Standard 2.0 库时出现问题

各位 MSFT 开发人员大家好, 为了您的方便,我创建了一个示例项目,可在 https://github.com/JiyaDesai-FandCo/WpfAppdotnet8 我们在库中有现有代码(类型为 .NET Standa...

回答 1 投票 0

如何在 ListBox 中的每个 ListBoxItem 之间放置分隔符?

这是我的 XAML: 这是我的 XAML: <ListBox Grid.Row="1" x:Name="lstGames" Background="#343434" > <ListBox.ItemTemplate> <DataTemplate> <Grid ShowGridLines="True"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Image Grid.Column="0" Source="{Binding ImageUrl}" Width="100"/> <StackPanel Grid.Column="1"> <StackPanel Orientation="Horizontal"> <TextBlock Text="Title:" /> <TextBlock Text="{Binding Title}" /> </StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock Text="Release Date:" /> <TextBlock Text="{Binding ReleaseDate}" /> </StackPanel> </StackPanel> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> Sans 在 DataTemplate 中放置一个矩形并为其赋予颜色,ListBox 是否有某种方法可以在每个项目之间本机设置某些内容? 这是一个更好的例子,因为顶部没有分隔符 <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <StackPanel> <Separator x:Name="Separator"/> <ContentPresenter/> </StackPanel> <ControlTemplate.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource PreviousData}}" Value="{x:Null}"> <Setter Property="Visibility" TargetName="Separator" Value="Collapsed"/> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> 这建立在 @EvaLacy 给出的答案的基础上,更加完整一些。 因为该答案替换了 ListBoxItem 的模板,所以它禁用了选择列表项时发生的内置突出显示(因为突出显示是通过原始模板中的触发器完成的)。要恢复此功能,请将默认触发器放入新模板中并稍微调整模板内容: <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <StackPanel> <Separator x:Name="Separator"/> <!-- Bind to parent properties --> <Border BorderThickness="{TemplateBinding Border.BorderThickness}" Padding="{TemplateBinding Control.Padding}" BorderBrush="{TemplateBinding Border.BorderBrush}" Background="{TemplateBinding Panel.Background}" Name="Bd" SnapsToDevicePixels="True"> <ContentPresenter Content="{TemplateBinding ContentControl.Content}" ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}" ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}" HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" /> </Border> </StackPanel> <ControlTemplate.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource PreviousData}}" Value="{x:Null}"> <Setter Property="Visibility" TargetName="Separator" Value="Collapsed"/> </DataTrigger> </ControlTemplate.Triggers> <!-- Original Triggers --> <Trigger Property="Selector.IsSelected" Value="True"> <Setter TargetName="Bd" Property="Panel.Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/> <Setter Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/> </Trigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="Selector.IsSelected" Value="True" /> <Condition Property="Selector.IsSelectionActive" Value="False"/> </MultiTrigger.Conditions> <Setter TargetName="Bd" Property="Panel.Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" /> <Setter Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/> </MultiTrigger> <Trigger Property="UIElement.IsEnabled" Value="False"> <Setter Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" /> </Trigger> </ControlTemplate> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> 我使用旧的但有用的向我展示模板应用程序检索了这些触发器。 我的解决方案: <Style x:Key="STYLE_ListBoxSubItem" TargetType="ListBoxItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter> <Setter Property="VerticalContentAlignment" Value="Stretch"></Setter> <Setter Property="SnapsToDevicePixels" Value="true"/> <Setter Property="OverridesDefaultStyle" Value="true"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <DockPanel LastChildFill="True"> <Separator x:Name="Separator" DockPanel.Dock="Top" BorderBrush="Black" BorderThickness="2"/> <Border x:Name="Border" SnapsToDevicePixels="true"> <ContentPresenter VerticalAlignment="Center" /> </Border> </DockPanel> <ControlTemplate.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource PreviousData}}" Value="{x:Null}"> <Setter Property="Visibility" TargetName="Separator" Value="Collapsed"/> </DataTrigger> <Trigger Property="IsSelected" Value="true"> <Setter TargetName="Border" Property="Background" Value="Orange"/> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="#888888"/> </Trigger> <Trigger Property="Control.IsMouseOver" Value="True"> <Setter TargetName="Border" Property="Background" Value="LightGray"></Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <!-- Usage --> <ListBox ItemContainerStyle="{StaticResource STYLE_ListBoxSubItem}"/> 您可以将分隔符的呈现移动到 ListBoxItem 控制模板中,如这个有意简化的示例所示: <Grid> <Grid.Resources> <PointCollection x:Key="sampleData"> <Point>10,20</Point> <Point>30,40</Point> <Point>50,60</Point> </PointCollection> </Grid.Resources> <ListBox ItemsSource="{StaticResource sampleData}"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <StackPanel> <Separator/> <ContentPresenter/> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> 这将使分隔符远离您的项目模板。代价是您可能需要从默认的 ListViewItem 控件模板复制更多内容才能满足您的需求。当然,Separator 是可视化渲染分隔符的十几种方法之一。 我们现在已经到达 Avalonia 11,您不再需要覆盖默认模板(默认模板可能会随时更改,然后您的覆盖可能会中断)。您现在可以设置默认模板的某些元素的样式。 <ListBox ItemsSource="{Binding Documents}"> <ListBox.Styles> <Style Selector="ListBoxItem"> <Setter Property="BorderBrush" Value="Black" /> <Setter Property="BorderThickness" Value="0,0,0,1" /> <Style Selector="^:nth-child(1)"> <Setter Property="BorderThickness" Value="0,1,0,1" /> </Style> </Style> </ListBox.Styles> 这为每个 ListBoxItem 提供了 1 的下边框,除了第一个也有上边框。

回答 5 投票 0

如何从代码隐藏中更改边框背景?

如何从代码后面将边框背景更改为红色? 如何从代码后面将边框背景更改为红色? <Border Name="border_c" HorizontalAlignment="Left" VerticalAlignment="Top" CornerRadius="10" Width="180" Background="green"> 试试这个.. using System.Windows.Media; Border border = border_c; SolidColorBrush redBrush = new SolidColorBrush(Colors.Red); border.Background = redBrush; 或 border_c.Background = Brushes.Red;

回答 1 投票 0

WPF MVVM ComboBox SelectedItem 不会从 ViewModel 传播到 View

我有一个 MVVM 绑定的 ComboBox 我有一个 MVVM 绑定的 ComboBox <ComboBox ItemsSource="{Binding RootPathItems, Mode=OneTime}" DisplayMemberPath="DisplayName" SelectedItem="{Binding SelectedRootPathItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsSynchronizedWithCurrentItem="True"> </ComboBox> 组合框中的所有项目都是内存唯一的,并在窗口启动时创建。 当用户更改下拉列表中的选择时,将调用 ViewModel 属性设置器,并将正确的对象提供给设置器。然后我根据选择开始一些同步操作,然后然后我想将选择更改为默认选择 private RootPathItem _selectedRootPathItem; public RootPathItem SelectedRootPathItem { get => _selectedRootPathItem; set { if (_selectedRootPathItem != value) { _selectedRootPathItem = value; this.OnPropertyChanged(); SomeAction(); } } } ... //in SomeAction(): this.SelectedRootPathItem = _nothingComboBoxItem; .Net 内部将再次调用属性 getter 并获取 _nothingComboBoxItem,但 UI 将保留在之前选择的项目上,不会切换到默认值。 我也尝试绑定SelectedIndex,效果相同。 我的猜测是因为当我设置一个新项目时我仍然在属性设置器调用堆栈中,这不起作用,但我实际上不知道这里出了什么问题。 仔细查看您的代码库并对其进行测试,在我看来,您关于“仍在属性设置器理论中”的说法是正确的。看来 WPF 不会更新视图,除非您将 this.SelectedRootPathItem = _nothingComboBoxItem 行放入任务中。 而且我还看到您尝试使用交互行为来订阅 ComboBox 的选择更改事件,我认为这是一个比在属性设置器中做很多事情更清晰的方法。这个想法怎么了?我看到 xaml 代码被注释掉了。 我添加了nuget包,将交互行为代码放回xaml中,删除了setter中的_rootPathItemSelectionChangedCommand.Execute(null);行,它完美地工作了。

回答 1 投票 0

WPF 文本多重绑定

当我使用多重绑定时,转换器无法正常工作 公共部分类 TestControl : UserControl { 公共 TestClass TimeData{get;set;} 公共测试控制() {

回答 1 投票 0

WPF 40 px 总是溢出右侧窗口

在我的WPF应用程序中,我有一个自己创建的小部件(甘特图)。 这是甘特图主窗口中的InitializeUI(): 私有无效InitializeUI(){ 画布=新画布 {

回答 1 投票 0

WPF DataGrid - RowDetails DataContext

背景 我有以下 DataGrid,其中有两列用于描述和状态。它们绑定到一个名为 RowViewModels 的 ObservableCollection ,它作为 ...

回答 1 投票 0

在我的 WPF 应用程序中托管 Windows Shell 资源管理器

是否可以在 WPF 或 WinForms 窗口中嵌入 Windows 资源管理器文件/文件夹浏览器视图? 我基本上想将文件/文件夹浏览器作为我的应用程序窗口的一部分托管。我不想重新

回答 4 投票 0

WPF TreeView:ExpandAll() 方法在哪里

如何展开WPF中的所有TreeView节点?在 WinForms 中,有一个 ExpandAll() 方法可以执行此操作。

回答 9 投票 0

将位图转换为位图图像

我有一个 BitmapImage 类型的可观察集合,其中存储了一些图像,该集合绑定到 UI。 现在的问题是,我想对这些图像进行更改,例如旋转......

回答 1 投票 0

WPF 根据所选项目组合框填充文本框

我制作了一个关于电影和演员的 WPF 项目(编程新手)。 现在我可以通过输入他的名字、国家、生日等来手动创建一个新演员(链接到电影)。因为我添加了更多内容并且

回答 4 投票 0

为什么绑定没有生效[重复]

我创建了 TextBox 类的派生类 MyTextBox,并添加了一个名为 AString 的依赖属性和一个名为 ContextChangedEvent 的路由事件。在XAML代码中,Text属性被绑定...

回答 1 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.