Blend 4 Beta: How to change image source as part of Timeline - wpf

I'm trying out Blend 4 beta, and looking for a way to do a simple thing:
When a mouse is hovered on an image,
the image should change its source to a different image.
When the MouseLeave happens, the image changes back.
I know I can do it in source code, but I'm looking for a code free way to do it, without hand coding xaml.
Blend 4 seems like the perfect fit. But I've tried to set this using Event Triggers that start stories, or using Visual States, but Blend does not seem to "remember" that the image source has changed. It remembers me changing other properties of the image (such as visibility, scale etc..) but Image source is what I'm after.
Is this a bug in blend, or am I doing something wrong?

One option is creating a custom action and attaching it to the image. It still involves code, but is kinda blendy.
public class ImageSwitchAction : TriggerAction<Image>
{
public ImageSource TargetImage { get; set; }
protected override void Invoke(object o)
{
AssociatedObject.Source = TargetImage;
}
}
After adding the class to your project and building, you can drag the new behavior to any image objects in the timeline, and configure the trigger and ImageSource in the action properties. In your case, add one action for MouseEnter and one for MouseLeave.

easy way:
first, subscribe the events of your image mouse enter and mouse leave then in this events
use image.setsource(new Uri(new image url)) to set the image source for each event
if u have troubles i can post real code here latter
regards
Rui

Related

How to refresh Winforms custom controls in Rider ide 2020.1.2

I am running JetBrains Rider 2020.1.2, Build #RD-201.7223.10, built on May 6, 2020 and working on a custom control. The IDE doesn't seem to update the property grid with design-time changes to my control. If I open and close the file, the changes will reflect. Whereas if I make the change and perform a build/run, changes will not reflect in properties grid for the control at design time. Is it possible for someone to cast some light on this?
[Category("Design"), Description("Turn on dark mode."),Browsable(true)]
public bool DarkMode { get; set; }
I.e. if I add the above.
It looks like there is a reload designer option in the top right.

Hosted Winform control does not respond to events from WPF

This is my first question in StackOverflow. Due to lack of reputations, I couldn't post any links or images.
I've been working on the following issue for more than 2 days. Any help would greatly be appreciated.
Before I get into my question, here is what I have and what I'm expecting:
I have a Windows Form which hosts WPF in an ElementHost control.
And then, I have a Winforms UserControl similar to DateTimePicker. This
is hosted inside a WindowsFormsHost control.
The above scenario is un-avoidable for the following reasons:
The authorization dialog to all our applications is developed in
Winforms, and takes a Winforms instance as its parameter. There is no
WPF version introduced yet. Therefore, I had to use an ElementHost to
host my View inside the Windows Form.
The Winforms control hosted inside my WPF is also un-avoidable. We
have our own DateTime Winforms UserControl that behaves similar to
the DateTimePicker Winforms control, but has lot more complexities
involved. So, replacing this control with a WPF version is out of
question.
Expected Functionality:
I have a
WPF control (say, a textbox)
A DateTime Winforms UserControl that I was mentioning above.
And a Cancel button that basically resets the above controls.
When I hit the Cancel button, I'm publishing an event from the ViewModel, say RunViewModel to the WPF UserControl code behind file, say RunView.xaml.cs.
eventAggregator.GetEvent<ResetDateTimeEvent>().Publish(true);
In the code behind file, I've subscribed to the event as follows
eventAggregator.GetEvent<ResetDateTimeEvent>().Subscribe(ResetDateTimeHandler);
The WPF control resets to its default value, but the DateTime UserControl does not reset.
So, for testing purposes, I removed the ElementHost control, and just had my WPF View with a WindowsFormsHost control that hosts the DateTime Winforms UserControl, and a WPF "Cancel" button.
When I click on the button, the value on the DateTime control resets to its default value.
Then, I thought this might be an issue with my DateTime Winforms UserControl.
So, I replaced my DateTime Winforms UserControl with a Winforms Textbox control in my actual application. So now the nesting is as follows:
WinForms-ElementHost-WPF-WindowsFormsHost-Winforms Textbox
Here is the xaml code.
<WindowsFormsHost x:Name="ReportFromDtTmHost" Margin="8,0" Grid.Column="0"
LostFocus="ReportFromDtTmHost_LostFocus">
<WindowsFormsHost.Child>
<winforms:TextBox x:Name="ReportFromDateTime"/>
</WindowsFormsHost.Child>
</WindowsFormsHost>
On Initial load, I’m loading the Textbox with Initial Load Text text
private void Window_Loaded(object sender, EventArgs e)
{
ReportFromDateTime.Text = "Initial Load Text";
}
As I was mentioning above, when I hit the Cancel button, this is what happens:
Publish the event from ViewModel
eventAggregator.GetEvent().Publish(true);
Subscribe to the event in the code behind file (xaml.cs):
eventAggregator.GetEvent().Subscribe(ResetDateTimeHandler);
EventHandler for the published event.
private void ResetDateTimeHandler(bool cancelClicked)
{
ReportFromDateTime.Text = "Reset to Default";
}
As you can see in the above code, I’m resetting the Text on clicking the Cancel button.
During Debugging, I could see the Text property being changed to "Reset to Default", but the UI does not show these changes.
Here is the wierd part:
The Child property on the WindowsFormsHost control is different from the actual “ReportFromDateTime” Textbox control.
While debugging, I could see that the Child and Name property on the WindowsFormsHost control were different.
The Name property is empty,
ReportFromDtTmHost.Child.Name = ""
which rather should be ReportFromDateTime.
It almost seems like the Host and the Child controls are getting re-created.
As far as I see it, I think the extra level of nesting (WinForms-ElementHost-WPF-WindowsFormsHost-Winforms Textbox) might be causing issues during the interoperations between WPF and Winforms.
I’ve done a lot of research and searched lot of links for suggestions. I found none pointing out this issue. Some of them were close. Here are a couple of links:
The this suggests to reproduce the message loop under the “Surrogate Windows Forma Message Loop” section.
Here is one more link that explains the issue with nesting under the Nesting section.
I apologize for being verbose. Just wanted you guys to get a clear picture of my problem. Please let me know if you have any questions regarding the post. Any suggestions would be greatly appreciated.
EDIT:
We were able to resolve the issue, but still, it is a work-around. Here is what we did:
There were two ways to resolve this issue, but both were related to using static.
Static Winforms control:
We used the following static Winforms control
public static class ControlHolder
{
public static TextBox ReportFromDateTimeInstance;
}
In the OnChanged event of the "actual" control, we dump the actual control, ReportFromDateTime to the static control, ReportFromDateTimeInstance.
private void ReportFromDateTime_TextChanged(object sender, EventArgs e)
{
ControlHolder.ReportFromDateTimeInstance = (TextBox)sender;
}
And from then on, wherever we update the actual control (as in ResetDateTimeHandler method), we update the static control
private void ResetDateTimeHandler(bool cancelClicked)
{
ControlHolder.ReportFromDateTimeInstance = "Text changed";
}
This shows the updated value on the Front-End
Static EventAggregator
This work-around was provided by one of our colleague.
In this case, we are using our actual control, ReportFromDateTime, rather than the static control, ControlHolder.ReportFromDateTimeInstance
We used a static event aggregator for publishing/subscribing the ResetDateTimeEvent instead of using the Event Aggregator instance provided by Unity Container. So, instead of
eventAggregator.GetEvent<ResetDateTimeEvent>.Publish(true);
we used:
ResetDateTimeEvent.Instance.Publish(true);
And in the subscription:
ResetDateTimeEvent.Instance.Subscribe(ResetDateTimeHandler);
I know that we need not use a static event aggregator in this scenario since we are using the instance provided by Unity Container (which makes sure that a single instance is shared by all the ViewModels), but this also has resolved the issue.
So, I'm still confused on why the above two scenarios are solving the problem. Is it the static-ness that is solving the issue ?
As I was already saying, I feel that the controls are getting re-created, and by the time we have the controls in hand, they have been already re-created.
Any suggestions would greatly be appreciated.
I've done the same thing before in an app that had a WPF control inside of a WinForms control. The WPF used Prism/Unity (later switched to MEF) to start everything up. However, this created a whole new EventAggregator by default in the bootstrapper, so I had override the default IEventAggregator in the container with a static one b/c the WinForm side had already been created and was using its own IEventAggregator instance. The symptom was similar in that published events were not received.
In a mixed system such as yours, singletons are great for ensuring that everything's feeding off of the same reference, especially when your startup is in stages (WinForms then WPF).
Simple answer: yes, use singletons for shared references between WinForms code and WPF code. Those singletons can be fed into the container in the WPF bootstrapper so that injection still occurs in the WPF side, too.

User control, custom control, inheritance and override

I know this question is probably going to get alot of "Duplicate question" comments but i have yet to see one with an answer that works or isn't simply "Avoid it at all cost". But here goes, i have created a control lets call it "ControlA" in a project called "ControlA_Project" and i was intending to override some of its virtual methods in a control called "ControlB" that inherites "ControlA" in another project called "ControlB_Project" . The idea being that "ControlA" has save and load methods that i wish to change from saving and loading to file, too saving and loading to database ( and if later on another save and load type is required i can just override those methods again ).
The problem i have is i originally had "ControlA" as a usercontrol and when i tried adding the new control with the overrides ("ControlB") into a window i would get this error:
The component 'ControlB_Project.ControlB' does not have a resource identified by the URI '/ControlA_Project;component/usercontrols/ControlA.xaml'.
Googling the error i came to the conclusion you could not inherit from a user control ( or for the sake of arguement it wasn't a good idea ). So i then changed the control from a user control to a custom control. this however then leads me to another problem, a template for a control doesnt link to the code behind (i.e On_Click) like it does in a user control and there is no easy way to simply override the behavier (as far as i am aware). I know i can retemplate ControlB by copy and pasting ControlAs template and changing a few lines but controlA has a large template as it is and making mutliple copies seems a waste of space.
So put simply is there a correct way to change the behavier of a control in wpf?
First, remember that the ControlTemplate can be changed by the user alot so you need to make sure that important fields are clearly marked.
So if you want an OnClick event. First mark your button as "important"
<Button x:Name="PART_MyButton"/>
Its also a good idea to mark this aswell on your control class
[TemplatePart(Name = "PART_MyButton", Type = typeof(Button))]
public class MyCustomControl : Control
Now you want to attach to the on click event of that button to do that, override the OnApplyTemplate method.
public override void OnApplyTemplate()
{
mButton = Template.FindName("PART_MyButton", this) as Button;
mButton.Click += MyEventHandler;
}
Depending on how well your control can work without the control, you should gracefully handle a not found control or throw an exception.
One final thing is. If you override a control which has a default style, it might be a good idea to provide a new default style.
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
and placing an implicit style in your generic.xaml

How to animate WPF WebBrowser

Just documenting this as a question an answer so that somebody else doesn't have to suffer the same pain.
I have a WPF application that animates pages, much like swiping on an iPhone. All was good until one of the pages needed to contain a WebBrowser. It did not respond at all well to the animation - when it was supposed to slide in, it wouldn't appear until you focused it, and when it was supposed to slide out, it would go away until you moved the mouse over it. In both cases it just popped in/out rather than animating.
Complicating matters, during the project it was decided to move back to .net 3.5 instead of 4 for unrelated reasons.
So the question is: how can I either (a) get the WebBrowser to properly animate; or (b) how can I hide the WebBrowser at the start of animation and show it again at the end. The animation is currently defined in XAML, and I don't particularly want to change it to code.
And a follow up question is: is there a better way, still using .net 3.5?
UPDATE The WPF WebBrowser is so pathetically lame compared to the WinForms one, I have swapped over, using WindowsFormsHost. Everything below still applies, but the WebBrowser is now not so nobbled (eg. it has a DocumentCompleted event).
I pretty quickly gave up on the option to animate the WebBrowser, as it just got all too hard, and instead decided to hide and re-show it. The start of the animation is triggered by a Command on the View Model. It then finds the page that should be displayed, creates it, and kicks off the animation through an attached property that reflects the transition state.
I created an interface, IRequireTransitionInfo, such that a call to IRequireTransitionInfo.TransitioningFrom gives it a chance to hide itself and IRequireTransitionInfo.TransitioningTo to show again. TransitioningFrom was easy, but TransitioningTo had to be called when the storyboard completed.
Initially, in the constructor of the View Model, it went looking for the Storyboard and hooked into its Completed event, as in the code below:
Storyboard animation = Application.Current.FindResource("SlideAnimation") as Storyboard;
if (animation != null)
{
animation.Completed += new EventHandler(animation_Completed);
}
And then the event handler:
void animation_Completed(object sender, EventArgs e)
{
IRequireTransitionInfo info = currentViewModel as IRequireTransitionInfo;
if (info != null)
info.TransitioningTo(currentView);
}
This seemed to be working pretty well with .net 4. After downgrading to .net 3.5, when the code above to hook up the Completed event ran, I got the following error:
Specified value of type 'System.Windows.Media.Animation.Storyboard' must have IsFrozen set to false to modify.
Despite some of the other answers on SO, you cannot unfreeze a frozen Freezable, and moving the code into the constructor of the MainWindow didn't help.
I went down the path of an attached property on the Storyboard that was bound to a command on the View Model.
<Storyboard x:Key="SlideAnimation" local:EventCommand.StoryboardCompleted="{Binding Source={StaticResource Locator}, Path=Current.MainViewModel.StoryboardCompletedCommand}">
However, this resulted in the following error at runtime:
Cannot convert the value in attribute 'ContentTemplate' to object of type 'System.Windows.DataTemplate'. Cannot freeze this Storyboard timeline tree for use across threads.
It seems you can't do any databinding on a Storyboard (under .net 3.5 at least). Consequently, I solved the problem somewhat inelegantly by having the attached property just define the string name of a resource that was expected to implement an interface supporting notification of storyboard completion.
<Storyboard x:Key="SlideAnimation" local:EventCommand.StoryboardCompletedHandler="Locator">
If anybody knows of a better way to handle this situation under .net 3.5, I would be glad to hear.

How do I hide the input caret in a System.Windows.Forms.TextBox?

I need to display a variable-length message and allow the text to be selectable. I have made the TextBox ReadOnly which does not allow the text to be edited, but the input caret is still shown.
The blinking input caret is confusing. How do I hide it?
You can do through a win32 call
[DllImport("user32.dll")]
static extern bool HideCaret(IntPtr hWnd);
public void HideCaret()
{
HideCaret(someTextBox.Handle);
}
When using the win32 call don't forget to hide the cursor in the textbox's GotFocus event.
Just for completeness, I needed such a functionality for using with a DevExpress WinForms TextEdit control.
They already do provide a ShowCaret and a HideCaret method, unfortunately they are protected. Therefore I created a derived class that provides the functionality. Here is the full code:
public class MyTextEdit : TextEdit
{
private bool _wantHideCaret;
public void DoHideCaret()
{
HideCaret();
_wantHideCaret = true;
}
public void DoShowCaret()
{
ShowCaret();
_wantHideCaret = false;
}
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
if (_wantHideCaret)
{
HideCaret();
}
}
}
To use the code, simply use the derived class instead of the original TextEdit class in your code and call DoHideCaret() anywhere, e.g. in the constructor of your form that contains the text edit control.
Maybe this is helpful to someone in the future.
If you disable the text box (set Enable=false), the text in it is still scrollable and selectable. If you don't like the visual presentation of a disabled text box (gray background usually) you can manually override the colors.
Be warned, manually overriding colors is going to make your form/control look weird on systems that do not use the default color/theme settings. Don't assume that because your control is white that everyone's control is going to be white. That's why you should always use the system colors whenever possible (defined in the System.Drawing.SystemColors enumeration) such as SystemColors.ControlLight.
I know this is an old thread but it is a useful reference.
I solved the problem with a much easier but very kludgie solution, which may depend on how much control you have over the user's access to the form. I added a textbox (any focus-able control) which I gave prime tabIndex value and then positioned it off-form so that it was not visible. This works fine on a dialog because the user can't resize. If the form is resizeable, this may not work.
As I said, a kludge - but a lot easier to set up. (BTW I found the HideCaret approach didn't work - but I didn't pursue it hard.)
AFAIK, this cannot be done. The TextBox control is a funny control because it actually has a lot of behaviour that can't be modified due to the way it taps into the operating system. This is why many of the cool custom TextBoxes are written from scratch.
I am afraid you may not be able to do what you wish to do :(

Resources