Friday, December 25, 2015

[WPF] Binding a Storyboard property relative to the target of the storyboard

In my search to achieve making application level storyboards with some changeable properties:

http://stackoverflow.com/questions/4472546/binding-a-storyboard-property-relative-to-the-target-of-the-storyboard


I have a storyboard which targets an element, and binds one of its own properties to a property on another element:

   
            Storyboard.TargetProperty="RenderTransform.X" 
            From="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualWidth}" 
            To="0" 
            Duration="0:0:5"/>
 
This storyboard works when the storyboard is stored in the resources of the window which holds the storyboard target. The 'From' value is correctly bound to the ActualWidth of the host Window instance.

However, I need to store the storyboard in my application level resources. From here, the storyboard does not seem to be able to target the window to determine the 'From' property. This is understandable as from inside , the binding won't be able to find an 'ancestor' of type Window.

I guess I need to be able to bind the 'From' value, relative to the target of the animation, rather than relative to the storyboard's DoubleAnimation.

Is this possible, and if so, how?

Here is the sample MainWindow.xaml:


    
     x:Key="localStoryBoard">
         
            Storyboard.TargetProperty="RenderTransform.X" 
            From="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualWidth}" 
            To="0" 
            Duration="0:0:5"/>
    
RoutedEvent="Button.Click"> Storyboard="{StaticResource centralStoryBoard}"/>
And here is an example app.xaml:
 x:Class="WpfApplication3.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    
        
         x:Key="centralStoryBoard">
             
                Storyboard.TargetProperty="RenderTransform.X" 
                From="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualWidth}" 
                To="0" 
                Duration="0:0:5"/>
        
    
This won't work, as the eventtrigger refers to the app.xaml version. If you change it to the local resource version, you can see it works.

[WPF] Binding to attached property

I'm trying to make a storyboard as an application resource where I can set a variable objects such as TO and FROM color transitions, the length of time between transitions, this seems like a good candidate:

http://stackoverflow.com/questions/19769263/binding-to-attached-property

I'm trying to bind from Button's ContentTemplate to attached property. I read all the answers for question similar to "binding to attached property" but I had no luck resolving the problem.
Please note that example presented here is a dumbed down version of my problem to avoid cluttering the problem with business code.
So, I do have static class with attached property:
using System.Windows;

namespace AttachedPropertyTest
{
  public static class Extender
  {
    public static readonly DependencyProperty AttachedTextProperty = 
      DependencyProperty.RegisterAttached(
        "AttachedText",
        typeof(string),
        typeof(DependencyObject),
        new PropertyMetadata(string.Empty));

    public static void SetAttachedText(DependencyObject obj, string value)
    {
      obj.SetValue(AttachedTextProperty, value);
    }

    public static string GetAttachedText(DependencyObject obj)
    {
      return (string)obj.GetValue(AttachedTextProperty);
    }

  }
}
and a window:
<Window x:Class="AttachedPropertyTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:AttachedPropertyTest"
        Title="MainWindow" Height="350" Width="525">
  <Grid>
    <Button local:Extender.AttachedText="Attached">
      <TextBlock 
        Text="{Binding 
          RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button},
          Path=(local:Extender.AttachedText)}"/>
    </Button>
  </Grid>
</Window>
That's pretty much it. I would expect t see "Attached" in the middle of the button. Instead it crashes with: Property path is not valid. 'Extender' does not have a public property named 'AttachedText'.
I've set breakpoints on SetAttachedText and GetAttachedText, and SetAttachedText is executed, so attaching it to button works. GetAttachedText is never executed though, so it does not find property when resolving.
My problem is actually more complicated (I'm trying to do binding from inside of Style in App.xaml) but let's start with the simple one.
Did I miss something? Thanks,




3 down vote accepted
Your attached property registration is wrong. The ownerType is Extender, not DependencyObject.
public static readonly DependencyProperty AttachedTextProperty = 
    DependencyProperty.RegisterAttached(
        "AttachedText",
        typeof(string),
        typeof(Extender), // here
        new PropertyMetadata(string.Empty));
See the MSDN documentation for RegisterAttached:
ownerType - The owner type that is registering the dependency property


[WPF] SharedSizeGroup IsSharedSizeScope Grid inside UserControl

While I can't confirm for sure that your requirement will work, I can confirm that as long as you set the Grid.IsSharedSizeScope Attached Property to True on a parent container control of both of the Grids that you have set up SharedSizeGroups for, then it should work. To find out for sure, just try it out... you could have probably tested it yourself quicker than the time it took you to write this question.

If there is no parent container control at the moment, just add one.... (put everything into it). The important thing to note here is that you're only supposed to set Grid.IsSharedSizeScope to True on the one single parent container control and not on every Grid.

SET Grid.IsSharedSizeScope in the PARENT control! NOT ON THE GRID ITSELF!

http://stackoverflow.com/a/26282796/2547795

[WPF] ListView Item spacing

Hopefully this will save someone else time. I found there are multiple 
properties that have to be set to 0 in order to completely remove the 
spacing between ListViewItems in a ListView control. In addition to 
Margin and Padding I had to set the BorderThickness to 0.  
 

     

     
 
http://stackoverflow.com/a/11423018/2547795 

Wednesday, January 9, 2013

C# .net Convert bool to int

bool theBool = true;
int boolToInt = theBool ? 1 : 0; //1 if theBool is true and 0 if theBool is false
that's it.

Tuesday, September 25, 2012

Failed to complete operation Visual Studio 2008 2010

Sometimes, when compiling and running a source code in Visual Studio, you get the error "Failed to complete operation" and the project will not run although you have build successfully. You'll know that the build is successful if you try to run the application by going to the BIN folder and running the compiled binary manually. I've been trying to find answers to this error but I've not bumped into a solution until now. Before I tell you the solution I've found, let me tell you how I usually fix it. To make the application run again, I try to do several things after and before I open Visual Studio.

1. If Visual Studio is already open and I'm feeling lazy, I try to do a Build > Clean Solution , then a Build > Rebuild All. This will usually not work. I follow this up by going to the bin folder and deleting the remaining files in the Bin folder. This will leave 1 file which is vshost.exe. If it still does not work, I run the vshost.exe manually.

2. If the above doesn't work (which usually doesn't). I have to close Visual Studio and delete the BIN and OBJ folders manually. This method worked 100% of the time.

This just sucks. There's also no log file that tells you what's wrong as far as I know.

AND NOW... let me tell you how to fix this permanently.

I was using a c# WPF for .net 4.0 project for this and I don't know if this is the same with other projects. I haven't had the need to investigate yet. Please comment if it works on other types of projects. Here are the Steps:

1. Go to the Property Pages of the project your working on. This can be done by selecting the project in the Project Explorer then going to View > Property pages or via the keyboard shortcut SHIFT+F4.

2. In the property pages, go to the Debug page and under Enable Debuggers, [UNCHECK] Enable the Visual Studio hosting process. Note: You'll have to do this for the target configuration (e.g. Release, Debug) or you can just select under the Configuration: pull down menu "All Configurations" to apply it across all future builds.

That's it. Please Comment if this worked for you.

Tags:
Program not running after Run or Compile F5
Failed to complete operation

Thursday, August 2, 2012

Errors encountered on Rx (Reactive Extensions) HOL (Hands on Lab)

Problems doing HOL
Error doing HOL
Hands on labs errors

Reactive extensions (Rx) in .Net intends to solve the nightmares of asynchronous programming. The concept is really new to me and I tried doing the Rx Team's HOL (Hands on Lab) for Rx in C#. Since the HOL was last updated a number of changes have been made. These are the troubles I encountered while doing the Rx HOL.

 1.
source.Run( x => Console.WriteLine("OnNext: {0}", x), ex => Console.WriteLine("OnError: {0}", ex.Message), () => Console.WriteLine("OnCompleted") );
Solution: Use ForEach or Do.
See: http://social.msdn.microsoft.com/Forums/en-US/rx/thread/398452c2-c97d-4d96-b784-2a2e8a026d12



2. Cannot create a breakpoint inside lambda expression, lambda statement:

Solution: The answer is actually on the HOL pdf. But if you are stupid like me and thought you could set a breakpoint the usual way then how wrong you are. It took me a few minutes to find out that a breakpoint cannot be set inside a lambda expression by clicking on the grey bar or by Pressing F9. The way to do it is to click inside a statement then press F9.

e.g. Click on the OnNext word inside WriteLine() then press F9.


3.  
var moves = Observable.FromEvent(frm, "MouseMove");
Solution: Use FromEventPattern instead. 
var moves = Observable.FromEventPattern(frm, "MouseMove");

4.
using (new CompositeDisposable(movesSubscription, inputSubscription))
Solution: Fully qualify it.
 using (new System.Reactive.Disposables.CompositeDisposable(movesSubscription, inputSubscription))

5.
var moves = Observable.FromEvent(frm, "MouseMove"); 
var input = Observable.FromEvent(txt, "TextChanged");
Solution: Same as 3. Use  FromEventPattern
var moves = Observable.FromEventPattern(frm, "MouseMove"); 
var input = Observable.FromEventPattern(txt, "TextChanged");

6. ObserveOn(lbl) error HOL.
using (input.ObserveOn(lbl).Subscribe(inp => lbl.Text = inp))
Solution: Make sure you add System.Reactive.Windows.Forms as a reference

7. DictServiceSoapClient not found
var svc = new DictServiceSoapClient("DictServiceSoap");
Solution: Add a add a "using"  to the header with the namespace of the service reference you created.
e.g.  using RxLab.DictionarySuggestService;


Tags: C# RX, c# reactive extensions