(I'm very very new to WPF and C#, so be gentle, please!)
I'm trying to create a "start page" for our application which will feature the 5 most-recently-used projects in hyperlink form (inside a TextBlock?).
There are bindings available already within the project. If I do a ListBox like this...
<TextBlock Margin="51,189,0,223.5" HorizontalAlignment="Left" Width="177" Background="#FFEBEAEA">
<ListBox Width="200" ItemsSource="{Binding RecentProjects}" ItemTemplate="{Binding}">
</ListBox>
</TextBlock>
...I get the full path of the previous projects. I'd like to strip them down to just the filename (and maybe even drop the extension) in hyperlink format, then set the action of the click to our "Open file" command with the filename as a parameter.
If anyone can guide me to good resources for doing non-web hyperlinks, acting on items within a collection, that would be really helpful.
Thanks!
Good question, your XAML would probably look like this:
<ListBox ItemsSource="{Binding RecentProjects}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Hyperlink Command="{Binding OpenCommand}">
<TextBlock Text="{Binding DisplayFileName}"/>
</Hyperlink>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And then the class would look like this:
class Class1
{
public List<Project> RecentProjects { get; set; }
public class Project
{
public ICommand OpenCommand { get; set; }
public Project()
{
OpenCommand = new RelayCommand(OpenFile);
}
public string FileName { get; set; }
public string DisplayFileName
{
get { return Path.GetFileNameWithoutExtension(FileName) ; }
}
public void OpenFile(object sender)
{
// Open the file here e.g.
Process.Start(FileName);
}
}
}
RelayCommand is a custom class detailed in the MVVM tutorial (http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090051) that will allow you to use delegates to deal with the commands.
Good luck!
Related
I am currently transferring my app from WinForms to WPF.
Since I'm new in WPF, I stucked at creating DataTemplates for my treeView items. The screenshot shows how my treeview looked in WinForms version, and I need to get close result in WPF.
(My WinForms treeview)
As you can see, my DataTemplate's logic should take into account these factors:
Node type / defines which icon and fields combination will be displayed for particular item (node). App has about 7-8 node types. Type stored in separate node's field.
Variable values / I need to replace with text if null, etc
Numeric variable values / e.g.: set gray color if zero, etc.
Other properties / e.g.: adding textblocks depending on boolean fields.
And so on...
All these factors result into huge amount of possible item params combinations.
Also I'm using DevComponents WPF DotNetBar AdvTree to divide item properties into columns. I presume I should create 'sub templates' for different field sets and compose from them the entire DataTemplate for each column.
I've learned about triggers, and have to say that implementing my logic with triggers will make my subtemplates huge anyway.
(Current state of my WPF treeview)
So here are my questions:
Are there any ways to dynamically compose complex templates with C# code (without creating raw XAML and loading it at runtime)?
Maybe I should use completely different way (instead of using DataTemplate)? In Winforms I just used OwnerDraw mode, so the task was MUCH easier than in WPF :(
And how to display nested properties inside template? e.g.: Item.Prop.Subprop1.Subprop2.Targetprop.
PS: English is not my first language, sorry for your eyes.
1) The answer is yes.
For exemple if you want to define a template in your window for a simple string
public MainWindow()
{
InitializeComponent();
DataTemplate template = new DataTemplate(typeof(string));
FrameworkElementFactory borderFactory = new FrameworkElementFactory(typeof(Border));
borderFactory.SetValue(Border.PaddingProperty, new Thickness(1));
borderFactory.SetValue(Border.BorderThicknessProperty, new Thickness(1));
borderFactory.SetValue(Border.BorderBrushProperty, Brushes.Red);
FrameworkElementFactory textFactory = new FrameworkElementFactory(typeof(TextBlock));
textFactory.SetBinding(TextBlock.TextProperty, new Binding
{
Mode = BindingMode.OneWay
});
borderFactory.AppendChild(textFactory);
template.VisualTree = borderFactory;
myControl.ContentTemplate = template;
}
And in the Window you just put something like
<ContentControl x:Name="myControl" Content="Test text" Margin="10"/>
Your content control will render the string surrounded by a red border.
But as you anc see it is really complex to define your templates in this way.
The only scenario where i could imagine this approache is for some kind of procedurally generated templates.
Another way is to generate a string for the template and then load it with XamlReader:
string xaml = "<Ellipse Name=\"EllipseAdded\" Width=\"300.5\" Height=\"200\"
Fill=\"Red\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"/>";
object ellipse = XamlReader.Load(xaml);
2) I don't really see the need to generate templates in code behind. For exemple for this kind of data structure:
public class User
{
public string Name { get; set; }
public User Friend { get; set; }
}
public class RootNode
{
public string Title { get; set; }
public User User { get; set; }
public List<Node> Nodes { get; set; }
}
public class Node
{
public string Title { get; set; }
public List<SubNode> SubNodes { get; set; }
}
public class SubNode
{
public string Title { get; set; }
}
You can define this type of template:
<Window
...
Title="MainWindow" Height="350" Width="525" >
<Window.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:RootNode}" ItemsSource="{Binding Nodes}">
<StackPanel x:Name="spContainer" Orientation="Horizontal">
<TextBlock Text="{Binding Title}"/>
<TextBlock Text="{Binding User.Friend.Friend.Name}"/>
</StackPanel>
<HierarchicalDataTemplate.Triggers>
<DataTrigger Binding="{Binding User}" Value="{x:Null}">
<Setter TargetName="spContainer" Property="Background" Value="Yellow"/>
</DataTrigger>
</HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:Node}" ItemsSource="{Binding SubNodes}">
<TextBlock Text="{Binding Title}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:SubNode}" ItemsSource="{Binding Nodes}">
<TextBlock Text="{Binding Title}"/>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView ItemsSource="{Binding RootNodes}"/>
</Grid>
</Window>
As you can see you can define a template by data type, you can also use triggers to modify the behavior in specific cases, you could also use som binding converters...
3) You can bind to nested properties just like to normal ones :
<TextBlock Text="{Binding User.Friend.Friend.Name}"/>
However in some cases more than two level bindings could fail (fail to resolve or fail to update when property changes, ...)
I am trying to make a program that gives you a CRUD interface for List of any objects you give it. That includes:
Showing all of their properties inside a ListBox
The ability to insert a new object
The ability to update an object
The ability to delete an object
Keep in mind that, at the compile-time, I have no idea what kind of objects I am getting. For example, I want to have a TextBlock for each of the properties simply listed inside ListBox's DataTemplate. So how would I do the data binding if I don't know the name of the property? Also, how would I generate an insertion form when I don't know property names?
And finally, is it possible to do it using pure MVVM Pattern, without any Code-Behind?
Thanks
One option: Wrap PropertyInfo in a PropertyInfoViewModel so you can bind to it's value:
class PropertyInfoViewModel
{
Object CRUDObject { get; set; }
PropertyInfo PropertyInfo { get; set; }
Object Value {
get
{
return PropertyInfo.GetValue(CRUDObject);
}
set
{
PropertyInfo.SetValue(CRUDObject, value);
}
}
}
You could have an ObservableCollection in your CRUDObjectViewModel, populated when you create it or change the CRUD it's attached to (Look up reflection if confused by this).
Use a template selector to choose a particular editor to display for the PropertyInfoViewModel:
public class PropertyTypeTemplateSelector : DataTemplateSelector
{
public DataTemplate BooleanTemplate { get; set; }
public DataTemplate GuidTemplate { get; set; }
public DataTemplate StringTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
PropertyInfo propertyInfo = (item as PropertyInfoViewModel).PropertyInfo;
if (propertyInfo.PropertyType == typeof(Boolean))
{
return BooleanTemplate;
}
else if (propertyInfo.PropertyType == typeof(Guid))
{
return GuidTemplate;
}
else if (propertyInfo.PropertyType == typeof(String))
{
return StringTemplate;
}
return null;
}
}
You could use it like this:
<ListBox ItemsSource="{Binding Properties}">
<ListBox.Resources>
<DataTemplate x:Key="BooleanTemplate">
<CheckBox Content="{Binding PropertyInfo.Name}" IsChecked="{Binding Value}"/>
</DataTemplate>
<DataTemplate x:Key="GuidTemplate">
<StackPanel>
<TextBox Text="{Binding PropertyInfo.Name}"/>
<TextBox Text="{Binding Value, ValueConverter={StaticResources MyGuidConverter}}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="StringTemplate">
<StackPanel>
<TextBox Text="{Binding PropertyInfo.Name}"/>
<TextBox Text="{Binding Value}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="Null"/>
</ListBox.Resources>
<ListBox.ItemTemplateSelector>
<helpers:PropertyTypeTemplateSelector BooleanTemplate="{StaticResource BooleanTemplate}"
GuidTemplate="{StaticResource GuidTemplate}"
StringTemplate="{StaticResource StringTemplate}"/>
</ListBox.ItemTemplateSelector>
</ListBox>
Might have to think about how to deal with changes/updates though, as this isn't using NotifyPropertyChanged to keep the UI up to date.
I've not tested any of this, but it should work, I think.
This control WPFCrudControl may fit with your problem.
A generic WPF CrudControl implemented based on the MVVM pattern. It gives a huge productivity boost for straightforward CRUD operations (Add, Edit, Delete, Validate, Listing with sorting, paging and searching). The control abstracts both the UI and business logic, so it requires relatively minimal coding effort, while keeping it possible to customize its behavior.
I am very new to WPF and testing some things that I would like to include in an application that I will be working on. I have a 2 row ListView (bound to a textbox) with the names Scott Guthrie and Jon Skeet in it. I am trying to select "Scott Guthrie" in the ListView and have it populate the TextBox. I want to be able to edit the text and tab off and have the ListView updated.
Edit:I removed the code since that really didn't add anything to the question.
Wow, that's really complicated what you've got there.
This can be accomplished in a very simple way. You need a model to represent the programmer, a view model to hold a list of programmers, and simple binding to take care of the rest.
The model:
public sealed class Programmer
{
public string Name { get; set; }
}
Its very simple. An object representing a programmer with a name. We must encapsulate the name within an object because strings are immutable in .NET. If you tried binding against a single string in a list of strings, changes wouldn't propagate.
The collection of programmers is kept in a ViewModel. In this case, I call it ViewModel, because I have no imagination. This view model contains everything that the view binds against. In this case, its the list of programmers.
public sealed class ViewModel
{
public ObservableCollection<Programmer> Programmers { get; private set; }
public ViewModel()
{
Programmers = new ObservableCollection<Programmer>();
}
}
The ViewModel is set as the DataContext of our view. The DataContext flows down the visual tree, and we can bind against it at any point.
public MainWindow()
{
var vm = new ViewModel();
vm.Programmers.Add(new Programmer { Name = "Jon Skeet" });
vm.Programmers.Add(new Programmer { Name = "Scott Guthrie" });
DataContext = vm;
InitializeComponent();
}
You can set the DataContext in any way you want; I'm doing it here for simplicity's sake.
In the UI, I simply bind the ListView against the list of Programmers in the ViewModel (the DataContext, unless otherwise stated, is the root of the binding path). I then bind the TextBox against the SelectedItem of the ListBox. You select a Programmer from the list, which then becomes the SelectedItem, which I can then change the Name of.
<Window
x:Class="Programmers.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:t="clr-namespace:Programmers"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ListBox
x:Name="list"
ItemsSource="{Binding Programmers}"
DisplayMemberPath="Name" />
<TextBox
Grid.Column="1"
VerticalAlignment="Top"
Text="{Binding SelectedItem.Name, ElementName=list}" />
</Grid>
</Window>
Simple, once you get the hang of it.
This works (except that you need to validate the textbox since you can enter any text.. a dropdown might be a better choice).
View:
<TabItem x:Name="RightTabPage" Header="RightModel" DataContext="{Binding Right}">
<StackPanel>
<TextBox Text="{Binding SelectedGuru}"/>
<ListView SelectedItem="{Binding SelectedGuru}" ItemsSource="{Binding Gurus}"/>
</StackPanel>
</TabItem>
ViewModel:
public class RightViewModel
{
public RightViewModel()
{
Gurus = new[] {"Scott Guthrie", "Jon Skeet"};
SelectedGuru = Gurus.First();
}
public string SelectedGuru { get; set; }
public IEnumerable<string> Gurus{ get; set; }
}
I have a simple ComboBox in my Silverlight 3 application. I want to populate it from an ObservableCollection. The list holds a class that has a Name(string), and a Selected(bool) property. The combo box has as many items as I have in the list, but I cannot seem to get the list data to appear.
Any help would be appreciated.
<ComboBox x:Name="cmbCategory" Grid.Column="3">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
<CheckBox IsChecked="{Binding Selected}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
...
private class cmbCategoryClass
{
public string Name { get; set; }
public bool Selected { get; set; }
}
private ObservableCollection<cmbCategoryClass> _categories;
....
cmbCategory.DataContext = _categories;
cmbCategory.ItemsSource = _categories;
I can't tell from your code if this is a Codebehind or a ViewModel. I am guessing that you are actually populating the _categories list in code so that it contains at least one cmbCategoryClass object. Try removing the line that sets the DataContext to _categories as your ItemsSource may be looking for a _categories property on the DataContext Check the Output window in Visual Studio when running in debug mode for clues to data binding failures.
I am trying to populate a datagrid (or gridview) as a child elment of a treeview from the database. I am able to get data from the DB in the tree, however, it doesnt seem to work for the datagrid. Here is my xaml code:
<Window x:Class="AttemptUsingHirarchichalData.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="clr-namespace:AttemptUsingHirarchichalData"
xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<HierarchicalDataTemplate DataType="{x:Type data:Root}"
ItemsSource="{Binding Path=RootList}">
<TextBlock Text="{Binding RootNode}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type data:Nodes}"
ItemsSource="{Binding Path=ChildList}">
<TextBlock Text="{Binding ChildNode}"/>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView Name="TreeView1">
<TreeViewItem ItemsSource="{Binding Path=RootList}"
Header="{Binding RootNode}"/>
<TreeViewItem ItemsSource="{Binding Path=dt_Age}"
Header="{Binding dt_Age}"/>
</TreeView>
</Grid>
My codebehind is something like this:
InitializeComponent();
Root obj_Root = new Root();
obj_Root.RootNode = "RootNode";
obj_Root.RootList = new List<Nodes>();
Class1 obj_Class1 = new Class1();
DataTable dt_Age = obj_Class1.GetAgeInComboBox();
for (int i = 0; i < dt_Age.Rows.Count; i++)
{
Nodes obj_AgeNode = new Nodes();
obj_AgeNode.ChildNode = dt_Age.Rows[i][0].ToString();
obj_Root.RootList.Add(obj_AgeNode);
Class1 obj_class = new Class1();
DataTable dt_name = new DataTable();
dt_name = obj_class.GetName(Convert.ToInt32(dt_Age.Rows[i][0]));
obj_AgeNode.ChildList = new List<Nodes>();
//gridv
for (int j = 0; j < dt_name.Rows.Count; j++)
{
Nodes obj_NameNode = new Nodes();
obj_NameNode.ChildNode = dt_name.Rows[j][0].ToString();
obj_AgeNode.ChildList.Add(obj_NameNode);
}
}
TreeView1.DataContext = obj_Root;
My Class file has this as a part of it:
public class Nodes
{
public string ChildNode { get; set; }
public List<Nodes> ChildList { get; set; }
}
public class Root
{
public string RootNode { get; set; }
public List<Nodes> RootList { get; set; }
}
public DataTable GetAgeInComboBox()
{
SqlDataAdapter da_Age = new SqlDataAdapter("select distinct Age from myfrstattemt", conn1);
DataTable dt_Age = new DataTable();
da_Age.Fill(dt_Age);
return dt_Age;
}
Please tell me how to implement it. I am new to this, so please excuse my stupid errors, and please try to explain in simple terms. Thank you.
This is what I actually need to do
The good news is that you're doing a lot more work here than you need to, which is probably why you're having trouble.
The bad news is that you should really study a little more about WPF to properly grok this and come up with a good approach that's clean and concise. I'll try and point you in the right direction.
Firstly, you should get your head around ItemsControl. It's a really powerful class and is the base class of many of the everyday controls you would use in a WPF application. You should understand how binding any collection (IEnumerable, IList, IBindingList etc) to the ItemsSource property of ItemsControl will cause child items to be created.
You should then understand (if you don't already) how data types are converted into UI elements via DataTemplates. This is a simple but powerful concept.
Then you should experiment with a small extension to the above, namely HeaderedItemsControl and HierarchicalDataTemplate. This will give you all the tools you need to use the TreeView in the way you want to.
At no point would you need to create any TreeViewItems in C# code. If you can get the underlying data objects to reflect the hierarchy you want to display (irrespective of whether each node is a simple text label or a data grid) then you can create hierarchical data templates for all levels and have WPF take care of binding everything and creating the TreeViewItems for you.
EDIT
I have some questions for your edited question:
What is the difference between Root and Nodes?
Do you have a class hierarchy that models the relationship between nodes? If so, just use that rather than copying the objects into instances of Root and Nodes. I'll give you a made up example.
Let's assume you have Customers who place Orders, and each order has Items.
public class Customer
{
public string Name { get; set; }
public IEnumerable<Order> Orders { get; set; }
}
public class Order
{
public DateTime PurchaseDate { get; set; }
public IEnumerable<OrderItem> Items { get; set; }
}
public class OrderItem
{
public string ProductName { get; set; }
public int Quantity { get; set; }
public double UnitPrice { get; set; }
public double TotalPrice { get; set; }
}
The above types represent a hierarchy. If you have a structure like this, then you can bind it directly to the UI. You don't need to create any Root or Node objects. This is the WPF way :)
(Note that if you don't have the above class hierarchy, you might set about creating one specifically for use in the UI. Read more about the MVVM pattern if you're interested.)
In your XAML you would define the TreeView as:
<TreeView x:Name="_treeView" ItemsSource="{Binding}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type data:Customer}"
ItemsSource="{Binding Path=Orders}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type data:Order}">
<StackPanel>
<TextBlock Text="{Binding PurchaseDate}"/>
<ListView ItemsSource="{Binding Items}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding ProductName}" />
<GridViewColumn DisplayMemberBinding="{Binding Quantity}" />
<GridViewColumn DisplayMemberBinding="{Binding UnitPrice}" />
<GridViewColumn DisplayMemberBinding="{Binding TotalPrice}" />
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
And in code-behind, you'd do something like this:
_treeView.DataContext = customers; // eg. IEnumerable<Customer>
Might be worth having a look at this post by Marlon Grech.