I have an application where I used caliburn.micro and I observed some strange behavior. I have a grid with two colums, which are set to be equally broad. In this grid, there are two ListBoxes (see image below).
Now, if an item gets added to one ListBox and the other is empty, the ListBox with the item gets as broad as the item and the other one gets smaller, which means that the two ListBoxes aren't equally broad anymore.
Now comes the weird part of the story. If I resize the window once before adding the item, everything works as expected.
I've extracted this example from a larger application where I observed the same behavior with ItemControlls and TreeViews. In my research I rebuilt this sample application with pure WPF and everything works fine. So I think this problem must be connected to caliburn.micro.
This is the XAML of MainView:
<UserControl x:Class="WpfResizeErrorTest.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Background="#FF3D3A3A">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ListBox Name="LeftItems" Grid.Column="0" Grid.Row="0" Margin="0,0,5,0" />
<ListBox Name="RightItems" Grid.Column="1" Grid.Row="0" Margin="5,0,0,0"/>
<Button Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Name="AddItem" Height="30" Margin="5,5,5,5" Content="Add Item" />
</Grid>
</UserControl>
And the code of the corresponding view model:
public class MainViewModel : Screen
{
public MainViewModel()
{
this.LeftItems = new BindableCollection<string>();
this.RightItems = new BindableCollection<string>();
}
public BindableCollection<string> LeftItems { get; set; }
public BindableCollection<string> RightItems { get; set; }
public void AddItem()
{
this.LeftItems.Add("This is a long text which is usually longer than the list box it comes in.");
}
}
Does anyone know what the problem could be?
A colleague of mine has found the solution. Caliburn.micro changes the value of the SizeToContent property of the Window object. You have to do this in the bootstrapper:
public class Bootstrapper : BootstrapperBase
{
public Bootstrapper()
{
this.Initialize();
}
protected override void OnStartup(object sender, StartupEventArgs e)
{
base.OnStartup(sender, e);
var settings = new Dictionary<string, object>
{
{ "SizeToContent", SizeToContent.Manual }
};
this.DisplayRootViewFor<MainViewModel>(settings);
}
}
And everything works as expected.
Related
I am still new to WPF and MVVM and am trying to keep the seperation between View and View Model.
i have an app, essentially a projects task list app, in this i create projects and within each project i can create a set of tasks. Most is working well, but essentially i cannot get a command binding on a checkbox in a user control to work using DP, inherited datacontext etc. i always ge a binding failed error when running the app. i am trying to bing to a command in the viewmodel of the view which contains the user controls.
i created a user control to pull the task data together in the view, the command is on the checkbox
<UserControl x:Class="TaskProjectApp.Controls.TaskControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TaskProjectApp.Controls"
mc:Ignorable="d"
d:DesignHeight="100" d:DesignWidth="300">
<Grid Background="LightBlue">
<StackPanel Margin="5,5,5,5">
<TextBlock x:Name="titleTB"
Text="title"
FontSize="20"
FontWeight="Bold"/>
<TextBlock x:Name="DescriptionTB"
Text="description.."
FontSize="15"
Foreground="DodgerBlue"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="priority"
Text="0"
FontSize="15"
FontStyle="Italic"/>
<CheckBox Grid.Column="1"
x:Name="iscomplete"
Command="{Binding SetComplete}"/>
</Grid>
</StackPanel>
</Grid>
</UserControl>
in the user control code behind i have set the DP and the set text function is working
namespace TaskProjectApp.Controls
{
/// <summary>
/// Interaction logic for TaskControl.xaml
/// </summary>
public partial class TaskControl : UserControl
{
public UserTask Task
{
get { return (UserTask)GetValue(TaskProperty); }
set { SetValue(TaskProperty, value); }
}
// Using a DependencyProperty as the backing store for Task. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TaskProperty =
DependencyProperty.Register("Task", typeof(UserTask), typeof(TaskControl), new PropertyMetadata(new UserTask()
{
Title = "title",
Description = "none",
Comments = "none"
}, SetText));
private static void SetText(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TaskControl task = d as TaskControl;
if (task != null)
{
task.titleTB.Text = (e.NewValue as UserTask).Title;
task.DescriptionTB.Text = (e.NewValue as UserTask).Description;
task.priority.Text = (e.NewValue as UserTask).Priority.ToString();
task.iscomplete.IsChecked = (e.NewValue as UserTask).IsComplete;
}
}
public TaskControl()
{
InitializeComponent();
}
}
}
now to make this work i set the binding of the user control in the window as so, the listview takes the usercontrols and implements the observable collection of tasks.
<Window x:Class="TaskProjectApp.Views.ProjectsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TaskProjectApp.Views"
xmlns:uc="clr-namespace:TaskProjectApp.Controls"
mc:Ignorable="d"
Title="ProjectsView" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<uc:ProjectControl Project="{Binding UserProject}" />
<StackPanel Grid.Row="1">
<TextBlock Text="Task List"/>
<ListView ItemsSource="{Binding Tasks}"
SelectedItem="{Binding SelectedTask}">
<ListView.ItemTemplate>
<DataTemplate>
<uc:TaskControl Task="{Binding}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Content="Add Task"
Command="{Binding NewProjectTask}"/>
<Button Content="Delete Task"
Command="{Binding DeleteProjectTask}"/>
</StackPanel>
</Grid>
</Window>
this seems to completely stop me using the command, i set the datacontext in the code behind, to the whole window
public partial class ProjectsView : Window
{
public ProjectViewModel ProjectViewModel { get; set; }
public ProjectsView()
{
InitializeComponent();
}
public ProjectsView(UserProject userProject)
{
InitializeComponent();
ProjectViewModel = new ProjectViewModel(userProject);
DataContext = ProjectViewModel;
}
}
and reading trying to solve this has shown that the usercontrol should inherit the datacontext of the parent window.
i have seen solutions using relative paths and DPs for the commands as well as people saying these are not needed just let the inherited datacontext handle it.
but i have tried all three an neither works.
the interface shows me a message box saying no datacontext found, although i notice this is the case when you set the datacontext in code behind and not the xaml.
the SetCommand is created in the projects view model and its a property not a field as i have seen this fail for that reason too.
namespace TaskProjectApp.ViewModels
{
public class ProjectViewModel
{
public UserProject UserProject { get; set; }
public ProjectViewModel(UserProject userProject)
{
UserProject = userProject;
Tasks = new ObservableCollection<UserTask>();
NewProjectTask = new NewProjectTaskCommand(this);
DeleteProjectTask = new DeleteProjectTaskCommand(this);
SetComplete = new SetCompleteCommand();
ReadTaskDatabase();
}
public ObservableCollection<UserTask> Tasks { get; set; }
public NewProjectTaskCommand NewProjectTask { get; set; }
public DeleteProjectTaskCommand DeleteProjectTask { get; set; }
public SetCompleteCommand SetComplete { get; set; }
public UserTask SelectedTask { get; set; }
public void ReadTaskDatabase()
{
List<UserTask> list = new List<UserTask>();
using (SQLiteConnection newConnection = new SQLiteConnection(App.databasePath))
{
newConnection.CreateTable<UserTask>();
list = newConnection.Table<UserTask>().ToList().OrderBy(c => c.Title).ToList();
}
Tasks.Clear();
foreach (UserTask ut in list)
{
if (ut.ProjectId == UserProject.Id)
{
Tasks.Add(ut);
}
}
}
}
}
if anyone can point out where i am going wrong tat will be great as i fear i am now not seeing the wood for the trees.
I found the solution thanks to Ash link Binding to Window.DataContext.ViewModelCommand inside a ItemsControl not sure how i missed it, maybe wrong key words. anyway because the datacontext of the usercontrol is being made into my data class in the observable list Tasks
<StackPanel Grid.Row="1">
<TextBlock Text="Task List"/>
<ListView ItemsSource="{Binding Tasks}"
SelectedItem="{Binding SelectedTask}">
<ListView.ItemTemplate>
<DataTemplate>
<uc:TaskControl Task="{Binding}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Content="Add Task"
Command="{Binding NewProjectTask}"/>
<Button Content="Delete Task"
Command="{Binding DeleteProjectTask}"/>
</StackPanel>
you need to use a relative path inside the user control to look up past the ItemTemplate to the ListView itself as this uses the viewmodel data context to bind to, so has access to the right level
<UserControl x:Class="TaskProjectApp.Controls.TaskControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TaskProjectApp.Controls"
mc:Ignorable="d"
d:DesignHeight="100" d:DesignWidth="300">
<Grid Background="LightBlue">
<StackPanel Margin="5,5,5,5">
<TextBlock x:Name="titleTB"
Text="title"
FontSize="20"
FontWeight="Bold"/>
<TextBlock x:Name="DescriptionTB"
Text="description.."
FontSize="15"
Foreground="DodgerBlue"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="priority"
Text="0"
FontSize="15"
FontStyle="Italic"/>
<CheckBox Grid.Column="1"
x:Name="iscomplete"
Command="{Binding DataContext.SetComplete, RelativeSource={RelativeSource AncestorType=ListView}}"/>
</Grid>
</StackPanel>
</Grid>
</UserControl>
this might be limiting in future as it measn the usercontrol will look for a listview to bind the command, but it solves the immediate issue.
I have both a DataGrid and a ComboBox on wpf UserControl.
namespace ApSap
{
public partial class DocumentView : UserControl
{
public Document document;
public DocumentView(Document selectedDoc)
{
document = selectedDoc;
InitializeComponent();
DocBrowser.Navigate(document.FilePath);
// shows only empty rows
SapGrid.ItemsSource = document.SapDocNumbers;
// shows list of values correctly
Combo.ItemsSource = document.SapDocNumbers;
}
}
}
The combo Box correctly displays the content of the public property "SapDocNumbers" (a list of integers),
However the datagrid only displays empty rows, albiet the correct number of them.
the XAML is as follows:
<UserControl x:Class="ApSap.DocumentView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
>
<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="1" Grid.Row="1">
<DataGrid AutoGenerateColumns="True" x:Name="SapGrid" Margin="10,10,10,10" >
</DataGrid>
<Button x:Name="CreateInvoice" Content="Create Invoice" Margin="10,10,10,10" />
<Button x:Name="Save" Content="Save and Exit" Margin="10,10,10,10" />
<ComboBox x:Name="Combo" Margin="10,10,10,10" />
</StackPanel>
</Grid>
Is there anything I am missing from XAML grid definition that would mean the combo works correctly, but the datagrid does not?
as requested here is the definition of the class:
public class Document : INotifyPropertyChanged
{
private int _docID;
private List<Int64> _sapDocNumbers;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public int DocID
{
get { return _docID; }
set
{
if (value != _docID)
{
_docID = value;
NotifyPropertyChanged();
}
}
}
public List<Int64> SapDocNumbers
{
get { return _sapDocNumbers; }
set
{
if (value != _sapDocNumbers)
{
_sapDocNumbers = value;
NotifyPropertyChanged();
}
}
}
Thank you
The answer to your question depends on the implementation of the collection item type.
ComboBox uses ToString () by default to represent the item.
And DataGrid renders the properties of the element - for each property there is a separate column.
If the element type has no properties, the DataGrid will not create columns and will not display anything.
For a more precise answer, show the type of the collection and the implementation of the type of its element.
Completion of the answer in connection with the clarification of the question:
You want to display the ulong collection.
This type has no properties and therefore autogenerating columns in the DataGrid cannot create columns.
For your task you need:
<DataGrid AutoGenerateColumns="False" x:Name="SapGrid" Margin="10" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Mode=OneWay}" Header="Number"/>
</DataGrid.Columns>
</DataGrid>
one final question, How do i get a blank row on the DataGrid so the user can add their own SapDocNumbers to the list ?
The item of the collection goes to the Data Context of the DataGrid row.
UI elements cannot edit their DataContext.
Therefore, for a string, you need to create a reference ty with a property of the desired type and edit this property.
And this type must have a default constructor.
Since the list can be used in several bindings, the type of the list should not be a simple collection, but an observable collection.
For examples used class BaseInpc
using Simplified;
namespace ApSap
{
public class DocumentRow : BaseInpc
{
private long _sapDocNumber;
public long SapDocNumber { get => _sapDocNumber; set => Set(ref _sapDocNumber, value); }
public DocumentRow(long sapDocNumber) => SapDocNumber = sapDocNumber;
public DocumentRow() { }
}
}
using Simplified;
using System.Collections.ObjectModel;
namespace ApSap
{
public class Document : BaseInpc
{
private int _docID;
public int DocID { get => _docID; set => Set(ref _docID, value); }
public ObservableCollection<DocumentRow> SapDocNumbers { get; }
= new ObservableCollection<DocumentRow>();
public Document()
{
}
public Document(int docID, params long[] sapDocNumbers)
{
DocID = docID;
foreach (var number in sapDocNumbers)
SapDocNumbers.Add(new DocumentRow(number));
}
public static Document ExampleInstance { get; } = new Document(123, 4, 5, 6, 7, 8, 9, 0);
}
}
<Window x:Class="ApSap.DocumentWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ApSap"
mc:Ignorable="d"
Title="DocumentWindow" Height="450" Width="800"
DataContext="{x:Static local:Document.ExampleInstance}">
<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="1" Grid.Row="1">
<TextBlock Margin="10,10,10,0">
<Run Text="DocID:"/>
<Run Text="{Binding DocID}"/>
</TextBlock>
<DataGrid AutoGenerateColumns="True" Margin="10"
ItemsSource="{Binding SapDocNumbers}"/>
<Button x:Name="CreateInvoice" Content="Create Invoice" Margin="10" />
<Button x:Name="Save" Content="Save and Exit" Margin="10" />
<ComboBox x:Name="Combo" Margin="10" />
</StackPanel>
<DataGrid Grid.Row="1" AutoGenerateColumns="True" Margin="10"
ItemsSource="{Binding SapDocNumbers}" VerticalAlignment="Top"/>
</Grid>
</Window>
P.S. Learn to set the Data Context and bindings to it. Using the names of UI elements, referring to them in Sharp is most often very bad code.
I have tried data binding in WPF.
But it is showing few errors.Please help me.
I am attaching the code.I have create a simple text block and tried to bind the string. Also I want to know how Windows.datacontext works? In my code it is giving an error. please help me out.
Xaml code
<Window x:Class="Shweta.DataBinding"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DataBinding" Height="300" Width="300">
<Window.DataContext>
<l:DataBinding />
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54*" />
<ColumnDefinition Width="224*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="59*" />
<RowDefinition Height="202*" />
</Grid.RowDefinitions>
<Grid Grid.Column="1" Grid.Row="1">
<TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
</Grid>
</Grid>
</Window>
**Code behind**
namespace Shweta
{
public partial class DataBinding : Window
{
public DataBinding()
{
InitializeComponent();
Setupviewmodel();
}
private void Setupviewmodel
{
TextString="this worked";
}
public string TextString{get;set;}
}
}
Okay so first of all read the error messages ... It clearly says that l is not defined in XAML but still you're trying to use it : <l:DataBinding />...
Fix this by declaring l in your XAML :
<Window x:Class="Shweta.DataBinding"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:l="<your l declaration"/>
Another thing is that you haven't implemented INotifyPropertyChanged so you'r value wont get updated anyway.
Implement this like such :
public partial class DataBinding : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
void NotifyPropertyChanged([CallerMemberName]string propertyName = "")
{
if ( PropertyChanged != null )
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
string text;
public string TextString
{
get { return text; }
set { text = value; NotifyPropertyChanged(); }
}
public DataBinding()
: base()
{
InitializeComponent();
Setupviewmodel();
// as #Nahuel Ianni stated, he has to set DataContext to CodeBehind
// in order to be able to get bindings work
DataContext = this; // <-- only if not binded before
}
public void Setupviewmodel() // forgot to to place ()
// produced error : `A get or set accessor expected`
{
TextString = "this worked";
}
}
Yet another thing is that you have to specify DataContext only when it's not the same as your code behind so you do not need this part :
<Window.DataContext>
<l:DataBinding />
</Window.DataContext>
You are not specifying the DataContext correctly as you are trying to set it up on XAML by using a namespace that has not been declared. For more info on XAML namespaces, check the following link.
In your example it would be on the xaml side:
<Window x:Class="Shweta.DataBinding"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DataBinding" Height="300" Width="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54*" />
<ColumnDefinition Width="224*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="59*" />
<RowDefinition Height="202*" />
</Grid.RowDefinitions>
<Grid Grid.Column="1" Grid.Row="1">
<TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
</Grid>
</Grid>
</Window>
And in your code behind:
namespace Shweta
{
public partial class DataBinding : Window
{
public DataBinding()
{
InitializeComponent();
this.DataContext = this; // Pay attention to this line!
Setupviewmodel();
}
private void Setupviewmodel()
{
TextString="this worked";
}
public string TextString{get;set;}
}
}
The difference with the original version is that I'm not specifying the DataContext on XAML but on the code behind itself.
The DataContext can be considered as the place where the view will retrieve the information from. When in doubt, please refer to this MSDN article or you could learn about the MVVM pattern which is the pillar of working with XAML.
In order to make this work you have to set the DataContext properly. I'd suggest to create a viewmodel class and bind to that. Also I initialized the binding in the codebehind because your namespaces are missing. You can do that in xaml aswell. For now to give you something to work with try this for your codebehind:
public partial class DataBinding : Window
{
public DataBinding()
{
InitializeComponent();
DataContext = new DataBindingViewModel();
}
}
public class DataBindingViewModel
{
public DataBindingViewModel()
{
Setupviewmodel();
}
private void Setupviewmodel()
{
TextString = "this worked";
}
public string TextString { get; set; }
}
And change your view to this:
<Window x:Class="Shweta.DataBinding"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DataBinding" Height="300" Width="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54*" />
<ColumnDefinition Width="224*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="59*" />
<RowDefinition Height="202*" />
</Grid.RowDefinitions>
<Grid Grid.Column="1" Grid.Row="1">
<TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="{Binding TextString, TargetNullValue=Test}" VerticalAlignment="Top" Width="68" />
</Grid>
</Grid>
Note that the Text property will only be set at initialization. If you want DataBinding at runtime your DataBindingViewModel will have to implememnt INPC and throw the PropertyChanged Event after setting the property bound to.
I have a ListBox, in which data are put. Simple strings, nothing extreme. But, the user chooses what the data will be and he can and two different (!!!) objects, which have the same name.
Example: It is used with connection with pictures. Every picture has a name. And the user selects pictures and adds them to the listbox. But, if he chooses two pictures with the same name, this happens what selecting items in the listbox:
What shall I do, in order to avoid this? I want only one highlighted and selected item.
The listbox is set on a single selection, and on the selection event, it says that only one item is selected. So it concerns only the highlight.
(using WPF, C#)
To avoid this you'll have to use a wrapper around your strings; your Picture objects seems a good start.
Here is a sample that illustrates the two approaches:
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:WpfApplication1">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListBox x:Name="list1" ItemsSource="{Binding Pictures1}" />
<ListBox x:Name="list2" ItemsSource="{Binding Pictures2}" Grid.Column="1" DisplayMemberPath="Name" />
<TextBox Text="{Binding Text}" Grid.Row="1"/>
<Button Content="+" Grid.Row="1" Grid.Column="1" Click="Button_Click"/>
</Grid>
</Window>
Code behind:
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;
using System.Windows.Controls;
using System.Collections.ObjectModel;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public class Picture
{
public string Name { get; set; }
}
public string Text { get; set; }
public ObservableCollection<string> Pictures1 { get; set; }
public ObservableCollection<Picture> Pictures2 { get; set; }
public MainWindow()
{
InitializeComponent();
Pictures1 = new ObservableCollection<string>();
Pictures2 = new ObservableCollection<Picture>();
DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Pictures1.Add(Text);
Pictures2.Add(new Picture { Name = Text });
list1.SelectedItem = Pictures1[0];
list2.SelectedItem = Pictures2[0];
}
}
}
You can also bind more info like the extension, size, or any property that can help the user.
Hope this helps...
I have a WPF DataGrid that increases in height when I add data to it that won't fit inside its initial height. I don't want the height to change unless the user increases the Window size. Is there a way to stop this auto-resize?
<Window x:Class="WpfDataGridSizeTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Loaded="Window_Loaded"
SizeToContent="WidthAndHeight">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0">
<DataGrid x:Name="wordsDataGrid" VerticalAlignment="Top" ItemsSource="{Binding}" MinHeight="100" SelectionMode="Single" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" >
<DataGrid.Columns>
<DataGridTextColumn Header="Column" Width="Auto" Binding="{Binding AString}"/>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</Grid>
</Window>
public partial class MainWindow : Window
{
MyList myList = new MyList();
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
wordsDataGrid.DataContext = myList;
for (int i = 0; i < 100; ++i)
{
myList.AddOne("blah blah");
}
}
}
public class MyList : ObservableCollection<AClass>
{
public MyList() { }
public void AddOne(string aString)
{
base.Add(new AClass(aString));
}
}
public class AClass
{
public string AString { get; set; }
public AClass(string aString)
{
AString = aString;
}
}
If I don't get you wrong, you want your DataGrid to be in centain Height initally, with some Empty Space below the DataGrid within the Windows...Then when resize the Window, the DataGrid will changes it size.
Add one more Row to the Grid, and define a MinHeight of that Row. Then set DataGrid to be VerticalAlignment = Stretch. Also set a default height size for the Window.
<Window x:Class="WpfDataGridSizeTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Loaded="Window_Loaded" Height="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition MinHeight="100"/>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0" VerticalAlignment="Stretch">
<DataGrid x:Name="wordsDataGrid" VerticalAlignment="Stretch" ItemsSource="{Binding}" MinHeight="100" SelectionMode="Single" AutoGenerateColumns="False" VerticalScrollBarVisibility="Auto" >
<DataGrid.Columns>
<DataGridTextColumn Header="Column" Width="Auto" Binding="{Binding AString}"/>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</Grid>
</Window>
I had the same problem, and I fixed it by simply removing SizeToContent="WidthAndHeight" in the Window definition.
This will do what you desire:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<DataGrid Name="dgMain" AutoGenerateColumns="True"></DataGrid>
</Grid>
alongside with this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Foo foo;
List<Foo> foos = new List<Foo>();
foo = new Foo() { Name = "Sjaak" };
foos.Add(foo);
foo = new Foo() { Name = "Joepie" };
foos.Add(foo);
dgMain.ItemsSource = foos;
}
}
public class Foo
{
public Foo() { }
public String Name { get; set; }
}
The trick is in the proportional (even) distribution of the row heights by using "1*" for the Height properties of both rows. You can also ditribute it in other "shares" by setting one row Height to "2*" etc.
If the problem is the entire grid growing (but you're happy for individual rows to grow) then: what's the parent panel that the DataGrid is inside? Changing this can affect the way the control resized.
For example: a StackPanel will allow its children to grow in one direction (the direction of stacking), and a DockPanel will limit the size of the "filled" element to the available space.
VerticalAlignment="Bottom"
worked for me to resolve this exact same problem. I also used
VerticalScrollBarVisibility="Auto"
Try using VerticalAlignment = Top for instance or explicitly set the Height property to some value.
This might also help to put the DataGrid in a StackPanel and controlling the sizing behavior of the StackPanel.
This answer maybe came late but hope it helps someone
what about creating a little method "ResizeDataGrid":
Private void ResizeDataGrid (DataGrid myTable,double currentWindowSize){
// How much size would your datagrid occupy of total size , 1: full window
var amountTakenofFullSize = 0.75;
//Change the amount taken so it fits to ur content
If(windowSize>800)
amountTakenofFullSize=0.85;
mainTable.Height=currentWindowSize * amountTakenofFullSize;
}
Then you can call it on window loaded or size changed
Call the method by using the paramètres :
ResizeTable(myDataGrid,(neededWindow).RenderSize.Height);