Adding item to collection does not refresh activity designer - workflow-foundation-4

Am re-hosting my designer and have added a toolbox item which has a WorkflowItemsPresenter to render multiple child activity items. So my model item has a collection as:
Sequence _innerSequence = new Sequence();
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(false)]
[Description("")]
public Collection<Activity> Activities { get { return _innerSequence.Activities; } }
and the binding is
<sap:WorkflowItemsPresenter Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" Items="{Binding Path=ModelItem.Activities}" VerticalAlignment="Center" HorizontalAlignment="Center" HintText="Drop activities here">
<sap:WorkflowItemsPresenter.SpacerTemplate>
<DataTemplate>
<Label HorizontalAlignment="Center" Height="21"/>
</DataTemplate>
</sap:WorkflowItemsPresenter.SpacerTemplate>
</sap:WorkflowItemsPresenter>
The binding works absolutely fine when the designer is loaded. Now i want to clear and add new items to this collection when some filter is updated on the designer. So in the set accessor of this filter property i call a method which does the following:
private void RefreshApplication()
{
Activities.Clear();
Activities.Add(new AddXYZApplication() { ApplicationName = "Test" });
}
Though the collection gets updated the designer does not refresh. I know there is a way of doing this by writing some designer code-behind (i.e. updating the collection via the model item tree), but I would ideally like to have NO code-behind and expect it work like any other WPF application.
Any help would be greatly appreciated as I have been trying to devise a way (using multi-binding, using eventing etc) from sometime now.
Cheerio,
V

Just to answer after my comment.
When you're editing through WorkflowDesigner you haven't an Activity per se. What you have is a ModelItem.
From the moment you load an activity to the designer, through WorkflowDesigner.Load(activity) you don't have an activity anymore, you just start editing a ModelItem.
You can access XAML through WorkflowDesigner.Text (after flush it) and do whatever you want with it. For example load it into an ActivityBuilder or WorkflowService but that is it.
Designers don't known, and never will, that activities have Collection<Activities>, Collection<Variable> or any other properties. They only know the ModelItem and the properties it has, period.
In resume: changes have to be made to ModelItem because it's what designers bind to.

Related

CollectionView template calls converter incorrectly

Xamarin.Forms 5.0.0.2012, Visual Studio 2019 for Mac 8.10.16
I am encountering a problem (on both iOS and Android, on both emulators and physical devices) trying to call a Converter in the XAML describing a new screen in our app. This is the markup:
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:internal="clr-namespace:Views.Shared"
x:Class="Views.EditPage">
<ContentPage.Resources>
<internal:PictureNameToImageSourceConverter x:Key="PictureNameToImageSourceConverter" />
</ContentPage.Resources>
...
<CollectionView
x:Name="picturesView"
ItemsLayout="HorizontalList"
HeightRequest="90">
<CollectionView.ItemTemplate>
<DataTemplate>
<Frame HasShadow="False" Padding="5">
<Image
HeightRequest="80"
Source="{Binding Path=., Converter={StaticResource PictureNameToImageSourceConverter}}" />
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
The CollectionView.ItemsSource value is set in code to a List<string> instance. When the List has no items, the screen displays correctly. When it does have items the app crashes as the screen appears. If I launch the app attached to the VS debugger, the screen freezes before the crash, and I never get any information.
This converter is well tested and is used several other places in the app with no problem. When I replace the Image with <Label Text="{Binding Path=.}"/> the text items are displayed as expected, so it doesn't look like a binding or Path syntax error.
Is there something I'm not seeing or not aware of in the markup that's causing this? Or can anyone suggest further debugging I haven't thought of?
UPDATE
A breakpoint on the very first line of the converter was never reached.
EDIT in response to comments:
From the EditPage codebehind:
public partial class EditPage : ContentPage
{
internal List<string> PictureNames;
...
protected override void OnAppearing( )
{
base.OnAppearing();
picturesView.ItemsSource = PictureNames;
}
The PictureNames property is actually set by a different Page to which one navigates from the EditPage:
private void saveSelection_Click(object sender, System.EventArgs args)
{
creator.PictureNames = new List<string>();
foreach (SelectableItem<Picture> item in pictureItems)
{
if (item.IsSelected)
{
creator.PictureNames.Add(item.Item.PictureName);
}
}
Navigation.PopAsync();
}
pictureItems is a List acting as a ListView.ItemsSource on that screen, where pictures are selected or unselected.
UPDATE
After much setting of breakpoints, I've determined that the line picturesView.ItemsSource = PictureNames; is where the crash happens. It seems odd that it only happens when the template is showing an Image, but not a Label, seeing that the converter is never actually called.
UPDATE
The trick of adding the delay did get me to the breakpoint. And what I found is more puzzling than ever: The value parameter being passed to the Convert method of our converter is null. This is the case whether coming back from the picture selection screen, or if I set the bound list in response to a Button rather than in OnAppearing, or if I just set it right in the page constructor.
In addition, when setting a breakpoint on the crashing line, when the display element in the template is a Label everything is as expected, but when the display element is an Image the debugger freezes when trying to look at those values. The problem is apparently something about the fact of calling a converter in this precise situation.
I tested that by adding a different converter to the template:
<CollectionView.ItemTemplate>
<DataTemplate>
<Frame HasShadow="False" Padding="5" HeightRequest="{Binding Path=., Converter={StaticResource PictureNameToHeightConverter}}">
<Label Text="{Binding Path=.}" />
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
Exactly the same result: The value parameter passed to the Convert method is null even though the same bound value in the same template instance is displayed in the Label. If I set a breakpoint on the line assigning the ItemsSource property as before, the debugger freezes.
UPDATE
Finally beginning to suspect that I'm triggering some corner case bug in the framework, I replaced the CollectionView with a CarouselView, and it works correctly:
<CarouselView
x:Name="picturesView"
HeightRequest="90">
<CarouselView.ItemTemplate>
<DataTemplate>
<Frame HasShadow="False" Padding="5">
<Image
HeightRequest="80"
Source="{Binding Path=., Converter={StaticResource PictureNameToImageSourceConverter}}" />
</Frame>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
I'm adding this as an update to the question rather than as an answer because I still don't actually know the explanation.
I've seen some odd behavior when updating page details in OnAppearing.
Hard to put a finger on exactly when there will be a problem, but the fact that you navigated to another page, so this is OnAppearing during the "back" from that other page is probably a factor.
Try this:
protected override void OnAppearing( )
{
base.OnAppearing();
Device.BeginInvokeOnMainThread( async () => {
// Let the page appear on screen, before setting ItemsSource.
await System.Threading.Tasks.Task.Delay(200);
picturesView.ItemsSource = PictureNames;
});
}
At minimum, this should allow Xamarin to reach the breakpoint in the converter.
——————-
UPDATE
I don’t see any obvious flaw in the code you’ve posted.
You’ve narrowed it down to the line it crashes on.
Yet a breakpoint at start of converter is never reached.
As you say, this is a puzzling combination of facts.
Here is a test to do:
Put breakpoint on the line that crashes.
Copy the values in the list, to a text editor.
Add a button on the current page, that when pressed, fills the list with those same strings, hardcoded as a literal, then sets the ItemSource.
Start over, but this time press the button - Does this work or crash?
That is, remove all the complexity of going to another page, querying values, returning to this page.
I bet this will work. Then you’d have the best situation for debugging: a case that works vs. one that doesn’t.
After that, its “divide and conquer”. Start making the working one more like the broken one, and/or vice versa, until the culprit is identified.
You could try to pass data with the ways below when you do the navigation.
One way is to set the BindingContext to the page which you want to navigate to.
Use the Navigation.PushAsync to navigate the page and reset the BindingContext before the page navigated. You could check the thread i done before for more details. Xamarin Public Class data how to acess it properly
Or you could try to binding to a path property using MVVM.
<Image HeightRequest="80" Source="{Binding path, Converter={StaticResource PictureNameToImageSourceConverter}}" />
Another way is to pass the data to the page which you want to navigate through a Page Constructor.
For more details of this way, check the MS docs. https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/hierarchical#passing-data-through-a-page-constructor
While it would be interesting to know why the CollectionView binding isn't behaving as expected in this specific situation, the number of hours spent trying to figure it out has definitely passed the point of diminishing returns, so I just added the images the old-fashioned way. I replaced the CollectionView with a StackLayout:
<StackLayout x:Name="picturesLayout" Orientation="Horizontal" />
And then just added framed images "by hand" in the OnAppearing method:
picturesLayout.Children.Clear();
foreach (string pictureName in PictureNames)
{
picturesLayout.Children.Add(new Frame { Padding = 5, HasShadow = false, Content = new Image { Source = ImageManager.ReadFromDisk(pictureName), HeightRequest = 80 } });
}
(ImageManager handles chores like keeping track of the full path to the appropriate directory.)

Caliburn.Micro messes up the conventional binding of a Button?

I have just fired up a WPF project and I want to use Caliburn.Micro.
I have a button
<Button Content="Button" Name="AppendData">
and in my ViewModel I have a method void AppendData(){..}
It doesn't work! There is no binding between the two! But when I do this
<Button Content="Button" cal:Message.Attach="AppendData()">
it suddenly works. What can be the cause of this?
Edit:
I have created a test application where the conventions doesn't work: http://ge.tt/8sNsu201?c
You can make it work, by replacing the controls in MyView with
<Button cal:Message.Attach="SetText()" Content="Button" HorizontalAlignment="Left" Margin="106,153,0,0" VerticalAlignment="Top" Width="75"/>
<Label Content="{Binding Text}" HorizontalAlignment="Left" Margin="124,104,0,0" VerticalAlignment="Top"/>
After taking a look at your source code, I noticed a major mistake which is causing all of this confusion:
public MyView()
{
InitializeComponent();
DataContext = new MyViewModel(); // SOURCE OF TROUBLE
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
In Caliburn.Micro you don't set the DataContext for your view manually like that, instead you let Caliburn.Micro use its conventions to find the appropriate view for your view-model, then it will bind the two together (by setting the view-model as the DataContext of the view), after that it will apply a number of conventions to make everything work correctly.
Explaining why using cal:MessageAttach() would work and directly using AppendData won't work would take a lot of explanation because it seems you don't know the basics of CM.
So I advise you to take a look at the documentation wiki first and go through the first 5 articles at least, then here is a hint that will help you discover why the first method worked and the second didn't:
Message Bubbling
Because this would expand the comments maximum length, I write it as an answer.
As you mentioned in your answer, doing DataContext = new MyViewModel() is a kind of code smell in CM. If you want to hook up it manually in your view, this would be the right way (view first). Check out the CM documentation regarding this one though, because I think there might be missing something:
var viewModel = new MyViewModel();
var view = this;
ViewModelBinder.Bind(viewModel, view, null);
You can accomplish this in the XAML of your view, either. Add the following into the UserControl tag of your view (view first, as well):
xmlns:cal="http://www.caliburnproject.org"
cal:Bind.Model="MyViewModel"
View model first would be done quite the same, in case you are not willing to use the default behavior you described in your answer:
xmlns:cal="http://www.caliburnproject.org"
cal:View.Model="MyViewModel"
I am not sure, but I think you have to add an explicitly named export contract to your view model, if you want to use View.Model or Bind.Model, but it might be it works without as well. Try it out:
[Export("MyViewModel", typeof(MyViewModel))]
public class MyViewModel : Screen
{
// ...
}
Design time views have nothing to do with view first or view model first though!
Design-time view support is accomplished as follows:
xmlns:cal="http://www.caliburnproject.org"
d:DataContext="{d:DesignInstance viewModels:MyViewModel, IsDesignTimeCreatable=True}"
cal:Bind.AtDesignTime="True"
I am currently not able to test all those things, so I hope there are not any mistakes!

How to pass data to a viewmodel in Caliburn.Micro

This is probably a very simple question, but at this time I have myself so confused I can't see the answer. Simply put, I have a window that contains a content control. I'm using Caliburn.Micro's conventions to "locate" the view.
The window looks like this:
<Window x:Class="Views.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox/>
<ContentControl x:Name="MyViewModel" Height="Auto" Background="Blue"/>
</Grid>
</Window>
The view itself is successfully found, and the screen displays as I expected. However, MyViewModel needs to make a service call to get information based on what is typed into the text box.
So, what I can't seem to figure out is how one would pass that information from the text box to the view model. I've thought of several options, but they all seem to be too much work which makes me think that I'm missing something simple.
Thanks a lot
Like you said there are a number of things you can do:
You could expose a property on MyViewModel and set it within
MainWindowView.
You could use the EventAgregator, publish an event from the
MainWindowView and subscribe to that event from MyViewModel.
Using MEF you could inject a shared resource between the two
ViewModels, set it in MainWindowViewModel, and be able to access it
from MyViewModel.

silverlight - binding to two objects

I want to create a user control, which can be bound to some data given from outside the control (requirement A), and some XAML properties must be bound to properties of the control itself (requirement B).
Let's say that I have a data class named StudentData and a control named StudentControl. I'm using this control inside a DataGrid. I put the StudentControl in the grid with a DataGridTemplateColumn. I somehow bind the StudentData in the current cell to the control. This is requirement A. This StudentControl wants to specify if some of the controls inside it are editable or not. The best way to do this is exposing a property, like StudentControl.AreSomeControlsEditable. Then I can bind the IsEnabled property of those controls to this property. This is requirement B.
Here's my first idea. I bind the current StudentData to a DP of StudentControl, then, inside the StudentControl, I change the data context to the control itself:
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TextBox
Content="{Binding Path=ExposedStudentData.Field1}" *reqA*
IsEnabled="{Binding Path=OtherProperty1}" /> *reqB*
</UserControl>
This way, I figured, the StudentControl gets the StudentData from outside, exposes this same StudentData and the other new properties (so the data and other properties are in one place now, not two), and then I can bind to these exposed properties in XAML (reqA+reqB are fulfilled at the same time). Except this doesn't work because of this bug. Basically, if I set the DataContext of the control to itself, then it gets set before the outer binding is applied. So if my binding path inside the cell is X, and then the data context changes, the binding engine will look for X in the new, self data context, and not the outer, grid data context.
Here's my second idea. I bind the current StudentData to the DataContext or a DP of the StudentControl. Then, to access other exposed properties of the StudentControl, I give a name to the UserControl and use ElementName binding:
<UserControl x:Name="self">
<TextBox
Content="{Binding Path=Field1}" *reqA*
IsEnabled="{Binding ElementName=self, Path=OtherProperty1" /> *reqB*
</UserControl>
This way, I figured, the current data context is the StudentData, and it's not changed, and I can bind to that with a simple path (reqA), and I can bind to the other exposed properties with the ElementName stuff (reqB). It works in basic scenarios, but not in a DataGrid, because of this bug. I'm guessing the problem arises when there are multiple controls with the same name in the visual tree.
I'm really starting to hate Silverlight, I started using it a month ago, and I already reported 9 bugs. Whenever I try to achive something other than a simple hello world application or something that Microsoft and everyone else seems to be using Silverlight for, I encounter a new bug. So what now, how would you bind to a data class given from outside the control and some other properties exposed by the control at the same time? Without, of course, setting up the bindings from code (which I'm doing now, but it's a nightmare with ListBoxes and DataTemplates) or not using binding at all.
I think your problem is with the DataContext and how it is inherited, as well as namescopes.
For the first, you should know that if a control doesn't specify its own DataContext, it will inherit that of its parent, and for ItemsControl derived controls, each Item will have its DataContext set to one of the data items in the ItemsSource collection.
For your second problem, if you're inside a DataTemplate, you're in a different namescope than outside of it. You can't access controls "by name" outside of a DataTemplate. What you can do here (for Silverlight 4 and below) is to traverse the Visual Tree yourself and look for the control you want. This, however, is going to become much easier and less painful with some new features in SL5, specifically the "FindAncestor" feature (which already exist in WPF).
Here's an article on MSDN about Namescopes in Silverlight. And here's another one about DataBinding which mentions how DataContext is inherited.
To achieve what you're looking for, I think this blog post should help you. It shows you how to implement "RelativeSource Binding with FindAncestor"-like behavior in Silverlight.
Hope this helps :)
On another forum, they told me to use MVVM. As it turns out, it can make my first idea a little better. Instead of binding my StudentControl to a StudentData, and then exposing this data and other properties, I should create a viewmodel, let's say StudentControlData, which contains a StudentData and additional properties required by the control. If I bind my control to this, then in the inherited data context of the control, I have access to all properties that I need. Now the only problem left is that inside a ListBox in my StudentControl, I lose this data context.

Entity graphy binding not working in deep level

Suppose I have entity graph like
People ->Student
then in xaml, I have following kind of binding(People is property of VM):
<TextBox Text="{Binding People.Name, Mode=TwoWay}" />
<TextBox Text="{Binding People.Student.StudentNo, Mode=TwoWay}" /> <!-- this bounding is not working -->
in VM, implementing IEditableObject. I have some code like:
public void BeginEdit()
{
((IEditableObject)this.People).BeginEdit();
((IEditableObject)this.People.Student).BeginEdit(); //this code not working
//....
}
When runing the app, all data bound to People is fine.
All data bound to Student is not working.
How to fix it?
I'd guess that the Student property is null on the client side. You need to add the [Include] attribute to the Student property on the server-side, so that it gets taken across to the client side by RIA services. You may also need to add an include for your server-side to retrieve it from the database, depending on how your data-access is written.

Resources