Dynamic Detail View C# Xaml - c#

I want to program a dynamic Detail View. Like a user clicked on an Item then he sees the detail view. Now he sees all Values, but when he only want to see a few values, he click on a config Button in this view and a second view opens where he can select and unselect all types of values. Like he dont want to see the Description, the he deselect it in the second view, and it´s no longer visible in the first view.
The only way for me to implement something like this is to programm a Function which generates the first view. The view would be a UI-Element. Which is then returned to the Windows where the UI-Element is set a child of an Element on the Window. But I think this isn´t a good way. How do you would solve this problem?
Thanks for every hint :)

If I understand well you want
List -> Details -> MoreDetails/Edit
Depending on what platform you are creating is a bit different but the idea is the following:
<ItemsControl ... x:Name="ItemsList" ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Tapped">
<core:InvokeCommandAction
Command="{Binding Datacontext.ShowItemDetails, ElementName=ItemsList}" CommandParameter="{Binding}"/>
</core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</Grid>
</DataTemplate>
</ItemsControl>
Now when you tap the grid you can show a PopupControl with the details and the DataContext:
public Command<ItemClass> ShowPopup
{
get
{
return new Command<ItemClass>((i)=>
{
//Create the Popup
});
}
}
In case you are not using MVVM you can add the Command in code behind and place in the page contructor this.DataContext = this; and place the previous command there.
And now create a control for the content of the popup, bind the properties to the item details, now add another behavior with a command in that control and unhide the controls for edit mode or more details mode

You could have for each detail item a property bool ItemXIsVisible which is bound to a checkbox in the config view, and to the IsVisible property of the X control in the detail view?

Related

WPF: Which solution? TabControl with close button and new tab button

I'm trying to find the best solution for a TabControl that both support a close button on each TabItem, and always show a "new tab button" as the last tab.
I've found some half working solutions, but i think that was for MVVM, that I'm not using. Enough to try to understand WPF =)
This is the best solution I've found so far:
http://www.codeproject.com/Articles/493538/Add-Remove-Tabs-Dynamically-in-WPF
A solution that i actually understand. But the problem is that it is using the ItemsSource, and i don't want that. I want to bind the ItemsSource to my own collection without having to have special things in that collection to handle the new tab button.
I've been search for days now but cant find a good solution.
And I'm really new to WPF, otherwise i could probably have adapted the half done solutions I've found, or make them complete. But unfortunately that is way out of my league for now.
Any help appreciated.
I have an open source library which supports MVVM and allows extra content, such as a button to be added into the tab strip. It is sports Chrome style tabs which can tear off.
http://dragablz.net
This is bit of a dirty way to achieve the Add (+) button placed next to the last TabItem without much work. You already know how to place a Delete button next to the TabItem caption so I've not included that logic here.
Basically the logic in this solution is
To bind ItemsSource property to your own collection as well as
the Add TabItem using a CompositeCollection.
Disable selection of
the Add(+) TabItem and instead perform an action to load a new tab when it
is clicked/selected.
XAML bit
<TextBlock x:Name="HiddenItemWithDataContext" Visibility="Collapsed" />
<TabControl x:Name="Tab1" SelectionChanged="Tab1_SelectionChanged" >
<TabControl.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding DataContext.MyList, Source={x:Reference HiddenItemWithDataContext}}" />
<TabItem Height="0" Width="0" />
<TabItem Header="+" x:Name="AddTabButton"/>
</CompositeCollection>
</TabControl.ItemsSource>
</TabControl>
The code behind
private void Tab1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Contains(AddTabButton))
{
//Logic for adding a new item to the bound collection goes here.
string newItem = "Item " + (MyList.Count + 1);
MyList.Add(newItem);
e.Handled = true;
Dispatcher.BeginInvoke(new Action(() => Tab1.SelectedItem = newItem));
}
}
You could make a converter which appends the Add tab. This way the collection of tabs in you viewmodel will only contain the real tabs.
The problem is then how to know when the Add tab is selected. You could make a TabItem behavior which executes a command when the tab is selected. Incidentally I recommended this for another question just recently, so you can take the code from there: TabItem selected behavior
While I don't actually have the coded solution, I can give some insight on what is most likely the appropriate way to handle this in a WPF/MVVM pattern.
Firstly, if we break down the request it is as follows:
You have a sequence of elements that you want to display.
You want the user to be able to remove an individual element from the sequence.
You want the user to be able to add a new element to the sequence.
Additionally, since you are attempting to use a TabControl, you are also looking to get the behavior that a Selector control provides (element selection), as well as an area to display the element (content) which is selected.
So, if we stick to these behaviors you'll be fine, since the user interface controls can be customized in terms of look and feel.
Of course, the best control for this is the TabControl, which are you already trying to use. If we use this control, it satisfies the first item.
<TabControl ItemsSource="{Binding Path=Customers}" />
Afterwards, you can customize each element, in your case you want to add a Button to each element which will execute a command to remove that element from the sequence. This will satisfy the second item.
<TabControl ...>
<TabControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=CustomerId}" />
<Button Command="{Binding Path=RemoveItemCommand, Mode=OneTime,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type TabControl}}"
CommandParameter="{Binding}" />
</StackPanel>
</DataTemplate>
<TabControl.ItemTemplate>
</TabControl>
The last part is a bit more difficult, and will require you to actually have to create a custom control that inherits from the TabControl class, add an ICommand DependencyProperty, and customize the control template so that it not only displays the TabPanel, but right next to it also displays a Button which handles the DependencyProperty you just created (the look and feel of the button will have to be customized as well). Doing all of this will allow you to display your own version of a TabControl which has a faux TabItem, which of course is your "Add" button. This is far far far easier said than done, and I wish you luck. Just remember that the TabPanel wraps onto multiple rows and can go both horizontally or vertically. Basically, this last part is not easy at all.

How to Create a View within a View WPF

I explain my issue as I'm quite new to UI design :
I have a main View which displays a TreeView on its left part. When an element is selected I'd like to show a description of the Item on the right on the same window. The design of this description depends on the nature of the Item.
So I created a View per Item Type corresponding to the different possible design.
Now When I click on the TreeView I have no idea how to show the corresponding view on the right of the same window. (I'm not asking about catching the event, just displaying a view within another view, like if I dynamically plotted a control).
Is it possible ? If not what kind of approach would you suggest ?
Many Thanks.
This seems like a great candidate for a Data Template.
Basically, create a content presenter and bind its content property to the TreeView's SelectedItem property. Now, create data templates for each of your types (using the DataType property) in the ContentTemplate property.
Now, the correct data template will be chosen with the correct data whenever you select something in your tree view.
As far as a separate dispatcher goes, I'm not sure, but I'm also not sure what scenario would require one.
More information can be found in this SO question.
Sample:
<ContentPresenter Content="{Binding Path=SelectedItem, ElementName=TreeView}">
<ContentPresenter.ContentTemplate>
<DataTemplate DataType="{x:Type Type1}">
<!-- Bunch of stuff-->
</DataTemplate>
<DataTemplate DataType="{x:Type Type2}">
<!-- Bunch of stuff-->
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>

How to translate ViewModel to Canvas in MVVM and WPF

I am new to WPF and MVVM, and would appreciate help with the following problem.
I want to create an application in which a user specifies – through a dialog - how he would like to layout N number of chart objects on a page, and the application shows him this layout on a canvas. When satisfied with the layout he sees in the canvas, the user persists it for later use.
All chart objects can be visualized as rectangles. User can also define a header, which too is a rectangle.
A typical layout could be the header at the top of the page, below which are three charts side-by-side. User would be able to specify this layout as well as dimensions and location of each child in a dialog, and then hit the ‘Apply’ button expecting to see this specification in graphical form on the canvas.
In my view model I would have a tree where the parent is the canvas, having one child of type header, and 3 children of chart type.
The user might not like what he sees, and make changes in the dialog which would then effect changes in the view model.
I kind of understand the View-ViewModel interaction between the dialog and the view model. But don’t know how to implement the Canvas-ViewModel interaction. Meaning that when the user requests in the dialog say a header rectangle of a given size at a given coordinate, I know how to add that header object in the tree in the view model, but I do not know how to then update the canvas from the ViewModel's tree. How would the canvas get drawn to reflect the object tree in the viewmodel, and then get re-drawn each time the viewmodel changes (as a result of user's interaction with the dialog)?
One option is to add the viewmodels to a collection, and then bind those to an ItemsControl. If you provide the appropriate datatemplates in the XAML, the views are automatically bound to the data. The Itemscontrol I have looks like this:
<ItemsControl x:Name="WorksetPresenter"
ItemsSource="{Binding ElementName=RootWindow, Path=TableauItems}"
>
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type viewModels:AnalysisViewModel}">
<wg:AnalysisView DataContext="{Binding DescriptiveAnalysis}"/>
</DataTemplate>
<!-- more datatemplates for more view/viewmodel pairs -->
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
TableauItems is an ObservableCollection<>. As soon as an ViewModel is added to the collection, it is rendered on the Canvas according to the View specified in the datatemplate. For positioning you can use e.g. the Canvas.Left and Canvas.Top properties (mind the alignment!), or a rendertransform.
You shouldn't store graphical settings such as size and coordinates of your controls in your viewModel.
If I were you I would approch this a bit differently.
In the View, Use DragAndDrop operations on the canvas to let the user change the location of the charts and header.
You can use GridSplitter to make them user-resizable
Then, when user hits Apply, Save the canvas object using XamlWriter.Save method
When you need it for later use, load it using XamlReader.Load method
In your ViewModel have a command that gets the canvas as a parameter and handles the Save operation.
Example
view:
<Canvas x:Name="mainCanvas">
<StackPanel>
<TextBlock Text="My Header ..."/>
<!-- Charts goes here .... -->
<Button Content="Apply">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding ApplyCommand}" CommandParameter="{Binding ElementName=mainCanvas}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</StackPanel>
</Canvas>
view model:
public class MainWindowViewModel
{
public MainWindowViewModel()
{
ApplyCommand = new DelegateCommand<Canvas>(canvas =>
{
string userLayout = XamlWriter.Save(canvas);
// save userLayout for later use ...
});
}
public DelegateCommand<Canvas> ApplyCommand { get; set; }
}
Hope this helps
If the application specifically deals with changes in layout and layout information is the data you are presenting, then putting layout information in your view model is certainly appropriate. However, simple presentation information does not belong in your view model.
For that you need a different solution. Consider this.
If I need to locate view model template location on screen, how do I do it? My view model cannot know about the visual tree! Bugger. To solve this, I tag elements with attached properties and use a custom layout behavior or control to query the attached properties.
This is very similar to how jQuery allows a javascript programmer to grab DOM elements from a web page.

How to bind a button on wpf grid to a method on MVVM when I am using caliburn micro

I have a Grid on a wpf window which I want to add the capability that user can delete some of the items by clicking on a delete button. The application uses Calibrun Micro to bind view to ViewModel.
My question?
1- Is it a good idea to use a button to delete an item from a grid in WPF?
2- How can I bind a button to a method on VM and in the methd get a pointer to the item that should be deleted?
Edit1
I added the buttons in this way to datagrid:
<DataGridTemplateColumn Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Delete" cal:Message.Attach="DeleteFromList($dataContext)" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
and c# code follow:
public void DeleteFromList(object tmp)
{
}
But the buttons on datagrid are disabled and clicking on them doesn't fire DeleteFromList method (I checked using debugger).
Why they are disabled? How can I make them enabled?
This depends on how your button is placed - is there a single 'delete' button or have you added a button per row in the grid (are we talking DataGrid or just Grid?)
Assuming you are talking about DataGrid, you can easily just add an action message command to the button and pass through the item which is being deleted to the message handler on the VM
e.g. in the VM
public class MyViewModel
{
public DataItemCollectionTypeName ItemCollection { get; set; }
public void DeleteItem(DataItemTypeName item)
{
ItemCollection.Remove(item);
}
}
Assuming ItemCollection is bound to the grid, the button XAML may look like this:
<Button cal:Message.Attach="[Click] = [DeleteItem($datacontext)]" />
You may also need to set Action.TargetWithoutContext (it should be bound to the VM) if this is a templated row, as otherwise CM will not be able to locate the VM to invoke the action message on
If you have a single button that isn't contained within the grid you can always target the grids SelectedItem in the action message
<DataGrid x:Name="SomeDataGrid"></DataGrid>
<Button cal:Message.Attach="[Click] = [DeleteItem(SomeDataGrid.SelectedItem)]" />
It may be (and probably is) the default property that CM will look at so you may not need to specify the property name unless you have modified default conventions
<DataGrid x:Name="SomeDataGrid"></DataGrid>
<Button cal:Message.Attach="[Click] = [DeleteItem(SomeDataGrid)]" />
Edit
To clarify: In order for CM to find a VM to call the DeleteItem method it uses the DataContext of the current item. In the case of an ItemsControl derived control, the datacontext for each item points to the item being bound, not the ViewModel.
In order to give CM a hint as to which object it should try to resolve the DeleteItem method on, you can use the Action.TargetWithoutContext attached property, which applies a target object for action messages without changing the DataContext of the bound row/item
You can use element name syntax to point to the correct place:
In this example I've used a grid as the root element and named it LayoutRoot, then I've pointed the action message target to LayoutRoot.DataContext (which will be the ViewModel) using ElementName syntax. You can use any method (AncestorType or whatever)
<Grid x:Name="LayoutRoot">
<DataGridTemplateColumn Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Delete" cal:Message.Attach="DeleteFromList($dataContext)" cal:Action.TargetWithoutContext="{Binding DataContext, ElementName=LayoutRoot}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</Grid>
That should then work!
You could do something like this...
<Button cal:Message.Attach="[Event MouseEnter] = [Action Save($this)]">
Check the docs as they will explain what you need to do and should answer your question: link

How to handle WPF event in MVVM for nested controls in a Window

FINAL NOTE
Final solution found in another post
Although I appreciated the clarification that was provided, the ultimate solution was in-fact provided by another solution as linked above. No matter WHAT I tried, the binding via the "Element Name" component was not working. I had to go based on the "Relative" hierarchy up the datagrid...
<Button Name="btnPrintReport"
Command="{Binding DataContext.MyPrintCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type DataGrid}}}"
CommandParameter="{Binding}"
Height="16" Width="16" HorizontalAlignment="Center" >
<Image Source="MyButtonImage.png" IsHitTestVisible="True"/>
</Button>
Hope something not too complicated in WPF / MVVM environment. Here's the scenario.
I have a Window (.xaml) and a corresponding View Model (.cs). The form displays fine with all the data bindings no problem. (note: this is NOT done via any commercial "framework" )
One of the controls that is in the view window is a custom user control of a datagrid with all pre-defined columns, headings and content to be displayed when the view is shown. This works all no problem even though the control is not directly "defined" in the main window .xaml file, but just dropped on the form as the user control itself (which has its own obvious .cs code-behind).
With the main window's "DataContext" pointing to the View Model, and the user control that has a datagrid
<DataGrid AutoGenerateColumns="False"
Name="dataMyStuff"
ItemsSource="{Binding Path=MyTablePropertyOnViewModel,
NotifyOnSourceUpdated=True,
NotifyOnTargetUpdated=True}" ... />
Now, what I'm looking for. On this data grid, I have a column that has an image in the first column. When I click on this image, I want to print a report specific to the record as represented by this row (it has a PK value I use). So, how do I tell the image "KeyUp" event to go to the View Model event handler since that is where the data is, and some other methods I'll need for preparing the call to the report. The view portion of the grid is for cosmetic display to the user, and thus no "functionality" directly in this control.
-- EDIT -- per progress from answers
I've adjusted my datagrid per comments from Josh and Rachel, however, something still does not appear to be quite right... Seeing the button was using a "Command" instance, I interpreted this as it needed to attach to an instance of an "ICommand" interface object on my view model. So, I created an instance. I know the command handler works as it is also used for common things like Add, Edit, Save, Cancel, Exit, etc... So I have a new one for this printing purpose. For simplicity, I have it created as an Always Execute, so there is no method to handle the "CanExecute" portion of the control. I've set the button's "Command" to almost all iterations I could think of an still nothing, but here's an update of what I'm seeing going on.
<UserControl>
<Data grid columns / template, etc to the button>
<DataTemplate>
<Button Name="btnPrintReport"
Command="{Binding DataContext.MyPrintCommand}" >
<Image Source="myPrintImage.png"/>
</Button>
</DataTemplate>
</Data grid columns, etc>
</UserControl>
In my ViewModel class (myICommandButtonHandler inherits from ICommand)
private myICommandButtonHandler myPrintCommand;
public myICommandButtonHandler MyPrintCommand
{
get { if (myPrintCommand == null)
myPrintCommand = new myICommandButtonHandler(myPrint);
return myPrintCommand;
}
}
private void myPrint()
{
MessageBox.Show( "Doing the print job..." );
}
Now, what I'm seeing. During step through initialization of all the controls and such. I click menu item to call my Window to be displayed. FIRST, it creates an instance of the View Model controller. THEN, it calls the Window and passes in the View Model controller as parameter so it is immediately set at the Window level as the "DataContext" of the window. The main window then goes into it's "InitializeComponents" call and starts to build out all the other controls embedded, including this separate class that contains the data grid in question. At the constructor of this usercontrol (that has the datagrid), there is no "data context" set yet as the rest of the controls have not been initialized yet, and I don't know why / when the "bindings" apparently get "hooked" in. So, it appears that trying to do the binding to the data grid's command button are failing. HOWEVER, at run-time, the actual data IS updated in the grid, so I know that much is working.
So, the data grid has its "ItemsSource" set to a property of a "DataView" property on the view model, but the binding of the "button" doesn't appear to see the "MyPrintCommand" handler that I thought would get the hit.. and its action is to just display a message box (for now).
Usually I use an AttachedCommand Behavior which allows me to bind Events to ViewModel Commands. For example, you could use
<Image ...
local:CommandBehavior.Event="KeyUp"
local:CommandBehavior.Command="{Binding DataContext.PrintCommand, ElementName=dataMyStuff}"
local:CommandBehavior.CommandParameter="{Binding }"/>
I'd would recommend using a different event than KeyUp, since I don't think Images can have Keyboard focus so the KeyUp event will never get fired.
A better alternative is to use a Button and overwrite it's Template to be your Image. This will maintain the Click functionality, and give you access to Command and CommandParameter properties
<Button Command="{Binding DataContext.PrintCommand, ElementName=dataMyStuff}"
CommandParameter="{Binding }">
<Button.Template>
<Image ... />
</Button.Template>
</Button>
Also, the CommandParameter="{Binding }" will simply pass the current DataRow's DataContext (your data object) to the command
Change the data template to be a button that has a image as its content. Use the command and commandparameter properties on the button to call your printing method. You can declare your print command in your viewmodel, and bind to it. Your parameter could be the selected row in your datagrid.

Categories

Resources