wpf 相关问题

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

错误“无法将 MessageBoxResult 转换为 Bool”

我收到错误“无法将 MessageBoxResult 转换为 Bool” MessageBox.Show("插入徽标?", "徽标", MessageBoxButton.YesNoCancel); if (MessageBoxResult.Yes) ...

回答 1 投票 0

Viewbox填充所有列网格空间WPF

我正在创建一个程序来告诉用户他的帐户余额之类的东西。我在带有 ViewBox 的网格上显示此信息(因此可以将其大小调整为任何屏幕分辨率),问题是......

回答 1 投票 0

WPF 组合框选择名称使用 ID

我有一个组合框,我试图在其中使用名称,但是当用户选择名称时,我想选择一个ID而不是名称。 这是我的 XAML: 我有一个 ComboBox,我尝试在其中使用名称,但是当用户选择名称时,我想选择 ID 而不是名称。 这是我的 XAML: <ComboBox x:Name="cb_tvrtkaID" Height="25" Margin="0,10,0,0" Loaded="cb_tvrtkaID_Loaded"/> 还有我的 C#: private void cb_tvrtkaID_Loaded(object sender, RoutedEventArgs e) { MSSQLConnect sql = new MSSQLConnect(); bool sqlIsConnected = sql.Connect(); string query = "SELECT tvrtkaId,tvrtkaNaziv from sifarnik.tvrtka"; SqlConnection connection = sql.GetConnection(); if (connection != null) { using (connection) { try { SqlCommand cmd = new SqlCommand(query, connection); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { cb_tvrtkaID.Items.Add(reader["tvrtkaNaziv"].ToString()); //cb_tvrtkaID.Items.Add(reader["tvrtkaId"].ToString()); cb_tvrtkaID.SelectedItem = reader["tvrtkaId"].ToString(); cb_tvrtkaID.DisplayMemberPath = reader["tvrtkaNaziv"].ToString(); } } } catch (Exception ex) { Debug.WriteLine(ex); } } } } 这给了我以下错误: System.Windows.Data Error: 40 : BindingExpression path error: 'Arbet-grad d' property not found on 'object' ''String' (HashCode=-1526763463)'. BindingExpression:Path=Arbet-grad d.o.o.; DataItem='String' (HashCode=-1526763463); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') System.Windows.Data Error: 40 : BindingExpression path error: 'Arbet-grad d' property not found on 'object' ''String' (HashCode=1553220975)'. BindingExpression:Path=Arbet-grad d.o.o.; DataItem='String' (HashCode=1553220975); target element is 'ComboBox' (Name='cb_tvrtkaID'); target property is 'NoTarget' (type 'Object') 如何解决此错误,以便显示名称但选择基础 ID? 一般来说,我建议用包含名称和 ID 的对象填充组合框。然后配置您的组合框以显示对象的名称。 <ComboBox x:Name="cb_tvrtkaID" Height="25" Margin="0,10,0,0" Loaded="cb_tvrtkaID_Loaded"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}" /> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> 组合框中的对象将由以下方式定义: class cbItem { public string Name{get;set;} public string ID; public cbItem(string name, string id) { Name=name; ID=id;} } 在您的代码中,您可以添加以下项目: //[...] while (reader.Read()) { cbItem myCbItem = new cbItem(reader["tvrtkaNaziv"].ToString(), reader["tvrtkaId"].ToString(); cb_tvrtkaID.Items.Add(myCbItem ); //from outside this method, you can find the item of your combobox whose ID property is x, simply by iterating or with the help of Linq cb_tvrtkaID.SelectedItem = myCbItem; } //[...] 每次使用 cb_tvrtkaID.Items.Clear() 从 SQL 加载时,不要忘记清理组合框项目。 例如,您可以使用绑定到 cbItem 列表和转换器来实现与上述相同的结果

回答 1 投票 0

我可以在 System.Speech.Synthesis 中使用 Windows 11 中添加的讲述人自然语音吗?

我想通过System.Speech.Synthesis提供的SpeechSynthesizer在WPF中添加TTS。 但是,Windows 11中添加的自然语音并不是新添加的,尽管更多的语音添加已经减少......

回答 1 投票 0

VS2019 - VSIX - 无法在运行时找到资源 (.png)

我尝试在基于 WPF 的 VSIX 中显示图像 在 XAML 设计器中,图像看起来不错 我尝试在基于 WPF 的 VSIX 中显示图像 在 XAML 设计器中,图像显示正常 <Image x:Name="waitImage" Source="pack://application:,,,/wpf/Resources/progress_1.png" /> 但是以编程方式,API 抱怨它需要程序集名称,所以我以这种方式加载它 Assembly assembly = Assembly.GetExecutingAssembly(); string assemblyName = assembly.GetName().Name; ImageAnimationPath = $"pack://application:,,,/{assemblyName};component/wpf/Resources/progress_{imageIndex}.png"; BitmapImage bitmapImage = new BitmapImage(new Uri(ImageAnimationPath)); imageIndex = (imageIndex % 3) + 1; 在运行时我收到一条错误消息: "Cannot locate resource 'wpf/resources/progress_1.png'." 我期望: 图像加载良好 并且在部署 VSIX 时或调试期间在运行时可用 我尝试过: 属性/副本始终在图像上 将构建操作设置为资源(图像从解决方案资源管理器中消失) 清洁溶液 任何帮助表示赞赏 您可以尝试以下代码。 如果“属性”窗口中的“构建操作”为“资源”: <Image Source="pack://application:,,,/AssemblyName;component/Resources/progress_1.png" /> 如果“构建操作”为“内容”并且“属性”窗口中的“包含在 VSIX 中”为 True: <Image Source="pack://application:,/Resources/progress_1.png" /> 以下是相应的代码隐藏方法,用于根据构建操作设置为资源还是内容来动态加载图像: 如果“属性”窗口中的“构建操作”为“资源”: using System; using System.Reflection; using System.Windows; using System.Windows.Media.Imaging; namespace YourNamespace { public partial class YourWindow : Window { public YourWindow() { InitializeComponent(); string assemblyName = Assembly.GetExecutingAssembly().GetName().Name; string imageUri = $"pack://application:,,,/{assemblyName};component/Resources/progress_1.png"; BitmapImage bitmapImage = new BitmapImage(new Uri(imageUri)); yourImageControl.Source = bitmapImage; } } } 如果构建操作是内容并且包含在 VSIX 中为 True: using System; using System.Windows; using System.Windows.Media.Imaging; namespace YourNamespace { public partial class YourWindow : Window { public YourWindow() { InitializeComponent(); string imageUri = "pack://application:,,,/Resources/progress_1.png"; BitmapImage bitmapImage = new BitmapImage(new Uri(imageUri)); yourImageControl.Source = bitmapImage; } } } 将 YourNamespace 替换为项目的实际命名空间,将 YourWindow 替换为窗口类的名称,将 yourImageControl 替换为图像控件的名称。这些代码隐藏方法根据构建操作配置动态加载图像。

回答 1 投票 0

LiveCharts2 HeatMap 数据工具提示格式错误

我正在使用 LiveCharts2 热图将数据放置到网格上,以便用户可以直观地看到并比较彼此相邻的值,就像它们在现实中出现一样。 有时颜色不够...

回答 1 投票 0

样式中WPF数据绑定的时序问题

我想在 WPF 绑定中立即进行数据验证,因此我在 UpdateSourceTrigger 中使用了 PropertyChanged。同时我想检测LostFocus,这是我修改DB的时间。而且,我

回答 1 投票 0

使用 TemplateColumns 将 WPF DataGrid 绑定到 DataTable

我已经尝试了一切但一无所获,所以我希望有人能给我一个顿悟的时刻。 我根本无法获得成功提取数据网格中数据的绑定。 我有一个数据表,可以...

回答 3 投票 0

如何将对象传递给 WPF 用户控件

我想做的就是将一个对象(在本例中是“Addon”的实例)传递到 UserControl(在本例中是“AddonControl”)并可以作为

回答 1 投票 0

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

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