Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all 18858 articles
Browse latest View live

Scrolling Issue in Virtualized TreeView

$
0
0

At .NET 4.0 . In a Vritualized TreeView(has 100000 items) ,  when  expanding a item - scroll position would jump to some other place making expanded node and its children NOT visible . Is there any way to fix this?



Interactivity in Framework 4

$
0
0

Hi,

I have problem with the following code when change the targeting framework from 4.5 to 4. The code is as below

<TextBox Grid.Row="2" Grid.Column="3" Text="{Binding CurrentPanditSearch.ProductLotF, TargetNullValue={x:Static sys:String.Empty}, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"  CharacterCasing="Upper"><i:Interaction.Triggers><i:EventTrigger EventName="LostFocus"><i:InvokeCommandAction Command="{Binding HinLotFormatCommandF}" CommandParameter="{Binding Source=F}"/></i:EventTrigger></i:Interaction.Triggers></TextBox>

I got  the following error message.

Error25The tag 'Interaction.Triggers' does not exist in XML namespace 'http://schemas.microsoft.com/expression/2010/interactivity'.

How can I do the same trigger mechanism in Framewrok4 ? Looking for a solution.

Thanks in advance

WPF: Could we simplify path definitions?

$
0
0

We have defined two paths for apply to two different styles.

The only difference between two paths is one path rotates 180 degree of first path.

So far we have to duplicate Path definition code and two paths difference in bold line section.

<Path x:Name="pathChrome" Data="M5.4907628E-15,85.783656 L-1.1796041E-14,15.481527 C-1.1796041E-14,15.481527 0.00046152103,-0.125 15.441696,-0.125 30.82625,-0.125 153.00691,0.12776899 153.00691,0.12776899 169.14967,0.12776899 169.5,15.491538 169.5,15.660051 169.5,27.792962 169.5,67.500033 169.5,85.783656" HorizontalAlignment="Left" Height="74.569" Stretch="Fill" StrokeThickness="1" VerticalAlignment="Top" Width="162" Margin="5,2.6,0,0" ClipToBounds="False" Opacity="1" Visibility="Hidden"><Path.Stroke><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="White" Offset="1"/><GradientStop Color="#FF8D8D8D"/></LinearGradientBrush></Path.Stroke><Path.Fill><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="#FF9E9E9E" Offset="0.004"/><GradientStop Color="#FFE2E2E2" Offset="1"/></LinearGradientBrush></Path.Fill></Path>
<Path x:Name="path" Data="M5.4907628E-15,85.783656 L-1.1796041E-14,15.481527 C-1.1796041E-14,15.481527 0.00046152103,-0.125 15.441696,-0.125 30.82625,-0.125 153.00691,0.12776899 153.00691,0.12776899 169.14967,0.12776899 169.5,15.491538 169.5,15.660051 169.5,27.792962 169.5,67.500033 169.5,85.783656" HorizontalAlignment="Left" Height="74.569" Stretch="Fill" StrokeThickness="1" VerticalAlignment="Top" Width="162" Margin="5,2.6,0,0" ClipToBounds="False" Opacity="1" Visibility="Hidden"
                      RenderTransformOrigin="0.5,0.5"><Path.Stroke><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="White" Offset="1"/><GradientStop Color="#FF8D8D8D"/></LinearGradientBrush></Path.Stroke><Path.Fill><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="#FF9E9E9E" Offset="0.004"/><GradientStop Color="#FFE2E2E2" Offset="1"/></LinearGradientBrush></Path.Fill><Path.RenderTransform><TransformGroup><RotateTransform Angle="180"/></TransformGroup></Path.RenderTransform></Path>

Is it possible that we can make the code simple? Thx! 


JaneC



Breaks when clicking on names in a ListView

$
0
0

So as the title suggests, I am having trouble when I select an item in a list view. If I click on the name of the item in the list, the program will break giving the following error/reason: 

An unhandled exception of type 'System.InvalidCastException' occurred in PresentationFramework.dll

Additional information: Unable to cast object of type 'System.Windows.Controls.ContentPresenter' to type 'System.Windows.Controls.Panel'.

If I click anywhere else on the line the item is on it will select the item just fine.

Another issue I am having is that when I try to check if the item is a directory after it is selected the program will break giving the following exception:

An unhandled exception of type 'System.NullReferenceException' occurred in Information.exe

Additional information: Object reference not set to an instance of an object.

Code:

private void ExploreDirectories2(TreeViewItem item)
        {
            var directoryInfo = (DirectoryInfo)null;
            if (item.Tag is DriveInfo)
            {
                directoryInfo = ((DriveInfo)item.Tag).RootDirectory;
            }
            else if (item.Tag is DirectoryInfo)
            {
                directoryInfo = (DirectoryInfo)item.Tag;
            }
            else if (item.Tag is FileInfo)
            {
                directoryInfo = ((FileInfo)item.Tag).Directory;
            }
            if (object.ReferenceEquals(directoryInfo, null)) return;
            try
            {
                foreach (var directory in directoryInfo.GetDirectories())
                {
                    var isHidden = (directory.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
                    var isSystem = (directory.Attributes & FileAttributes.System) == FileAttributes.System;
                    if (!isHidden && !isSystem)
                    {
                        expanded_directory.Items.Add(this.GetItem(directory));
                    }
                }
            }
            catch (IOException)
            {
                verify1 = false;
            }
        }

        private void ExploreFiles2(TreeViewItem item)
        {
            var directoryInfo = (DirectoryInfo)null;
            if (item.Tag is DriveInfo)
            {
                directoryInfo = ((DriveInfo)item.Tag).RootDirectory;
            }
            else if (item.Tag is DirectoryInfo)
            {
                directoryInfo = (DirectoryInfo)item.Tag;
            }
            else if (item.Tag is FileInfo)
            {
                directoryInfo = ((FileInfo)item.Tag).Directory;
            }
            if (object.ReferenceEquals(directoryInfo, null)) return;
            try
            {
                foreach (var file in directoryInfo.GetFiles())
                {
                    var isHidden = (file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
                    var isSystem = (file.Attributes & FileAttributes.System) == FileAttributes.System;
                    if (!isHidden && !isSystem)
                    {
                        expanded_directory.Items.Add(this.GetItem(file));
                    }
                }
            }
            catch (IOException)
            {
                verify2 = false;
            }
        }

        private void directory_tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            expanded_directory.Items.Clear();
            var tree = (TreeView)sender;
            var selected = (TreeViewItem)tree.SelectedItem;
            selected.BringIntoView();
            ExploreDirectories2(selected);
            ExploreFiles2(selected);
        }

        private void expanded_directory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                var list = (ListView)sender;
                var selected = (TreeViewItem)list.SelectedItem;
                if (selected.Tag is DirectoryInfo)
                {
                    if (selected.IsExpanded)
                    {
                        list.SelectedIndex = -1;
                    }
                }
            }
            catch(InvalidCastException)
            { }
        }

        private void expanded_directory_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var list = (ListView)sender;
            var item = (TreeViewItem)list.SelectedItem;
            if (item.Tag is DirectoryInfo)
            {
                expanded_directory.Items.Clear();
                ExploreDirectories2(item);
                ExploreFiles2(item);
            }
        }

If you would like to view the entire program you can download it here:  https://drive.google.com/file/d/0B2h5hXOyNkgfWjU4emlVNlo3ZWc/view?usp=sharing

If you do download it, you may need to comment out the if statement in expanded_directory_SelectionChanged function. That is the one that won't let me check if the item is a directory.

Let me know if you need anything!

Thanks,

Jesse


Copy/paste full row, full column, a cell on datagrid using MVVM?

$
0
0

What is the best way to implement on datagrid? As I am new on this, I had some researches but I am confused because there are some complicated implementations and easy ones? I try to understand the best way.

Adding simply selection mode and selection Unit doesnt help. Because it only copies the row but I cant paste it simply as a new row.

 SelectionMode="Extended" SelectionUnit="FullRow"  >

this approach in the article looks old to me. Not sure if there is anything new and much easier with newest framework. I am using MVVM light in my project.Attached is the sample project similar to my original project. can you please recommend me the best way for the following?

- Full Row(s) copy-paste

-1 or multiple columns copy-paste (optional)

- cell copy-paste


"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

Keeping the last value of binding in XAML?

$
0
0

I have got a rectangle as,

<Rectangle x:Name="llpadRect" Width="185" Height="{Binding b2}" Stroke="Black" StrokeThickness="1"  Canvas.Left="{Binding (Canvas.Left), ElementName=llpadSVRect}" Canvas.Top="900"/>

It's height is binded to,

            private double _b2=100;

            public double b2
            {
                get { return _b2; }
                set
                {
                    _b2 = value;
                    NotifyPropertyChanged();
                }
            }

And it's initialized with a value of 100. But in VS designer, the height of the rectangle is 0. Only during runtime it becomes 100. Is there a way that it'll stay 100 in VS as well?

KeyChar in WPF

$
0
0

In C# i have this code:

if (CheckNum(e.KeyChar.ToString()) == false)

public bool CheckNum(string str)
        {
            int r = 0;
            if (int.TryParse(str, out r) == true)
                if (r > 0 && r < 10)
                    return true;
            return false;
        }

the keyChar that was pressed is sent to CheckNum function to check if it's a number. 

the method TryParse is supposed to parse from the KeyChar to int.

it works great!

now when i want to write the same thing in WPF i have a problem:

this is the code:

if (CheckNum(e.Key.ToString()) == false)

public bool CheckNum(string str)
{
    int r = 0;
   if (int.TryParse(str, out r) == true)
        if (r > 0 && r < 10)
            return true;
    return false;
}

in wpf there is no KeyChar so i used Key, but the TryParse doesn't parse from Key to Int.

Magnus what do you suggest ?

WPF TextBox insert new text

$
0
0

When inserting a number in my textBox and then another number, for ex. 6 and then 3 I see: 63.

but i want that when I insert 6 and then 3 to see only: 3. 

i mean, that every Key comes instead of the one before and not added.

what should i do?


How to stop the rehreased powerpoint or set focus out of the powerpoint in C# ?

$
0
0

I am playing powerpoint in my window.


As you can see in this image window has two section, one is on the top that has tool bar where i have option like text, start button and etc. Now if my powerpoint is rehearsed in that case when i click on the text powerpoint should not be in active state ( it should be in deactivate state). but when i click on the start button it should be activated (rehearsed powerpoint should play). By default when this window launch focus is on start button.

What is happening here : When i click on text powerpoint is activated. that i dont want. how can i achive that ?

This is code that i am using on MouseLeftButtonDown event on the text :

 private void txtPlayingAudio_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
        PrerecordTooltip.Text = "Click to pause audio";
        BrushConverter bc = new BrushConverter();
        txtPlayingAudio.Foreground = (System.Windows.Media.Brush)bc.ConvertFrom("#007dc7");
        btnStart.Focus();

}}


Thanks




Setting WPF Datagrid Column Header Background and Foreground in Datagrid's Resources

$
0
0
Hi,

I have a WPF Datagrid in my GUI in which every datagrid column's header background and foreground property are bound to displayindex property of parent column using converters like below:
<DataGridTemplateColumn Header="MyColumnHeaderBinding"
                                        DisplayIndex="{Binding DataSource.Col1DispIdx, Source={StaticResource DataContextProxy}, FallbackValue=1, Mode=TwoWay}"
                                        Width="{Binding DataSource.Col1Width, Source={StaticResource DataContextProxy}, FallbackValue=Auto, Mode=OneWay}"
                                        Visibility="{Binding DataSource.Col1Visible, Source={StaticResource DataContextProxy}, Converter={StaticResource BoolToVisConverter}, Mode=TwoWay}"
                                        SortMemberPath="Col1"><DataGridTemplateColumn.HeaderStyle><Style TargetType="{x:Type DataGridColumnHeader}"><Setter Property="VerticalContentAlignment" Value="Center"/><Setter Property="Foreground" Value="{Binding DataSource.Col1DispIdx, Source={StaticResource DataContextProxy}, ConverterParameter=CLRHF, Converter={StaticResource DataContextProxy}}"></Setter><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type DataGridColumnHeader}"><Grid><Themes:DataGridHeaderBorder BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"
                                                         Background="{TemplateBinding Background}" IsClickable="{TemplateBinding CanUserSort}"
                                                         IsPressed="{TemplateBinding IsPressed}" IsHovered="{TemplateBinding IsMouseOver}"
                                                         Padding="0" SortDirection="{TemplateBinding SortDirection}"
                                                         SeparatorBrush="{TemplateBinding SeparatorBrush}"
                                                         SeparatorVisibility="{TemplateBinding SeparatorVisibility}"><Border Background="{Binding DataSource.Col1DispIdx, Source={StaticResource DataContextProxy}, ConverterParameter=CLRHB, Converter={StaticResource DataContextProxy}}" Margin="0,0,0,0"><ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/></Border>  </Themes:DataGridHeaderBorder><Thumb x:Name="PART_LeftHeaderGripper" HorizontalAlignment="Left" Style="{StaticResource ColumnHeaderGripperStyle}"/><Thumb x:Name="PART_RightHeaderGripper" HorizontalAlignment="Right" Style="{StaticResource ColumnHeaderGripperStyle}"/></Grid></ControlTemplate></Setter.Value></Setter></Style></DataGridTemplateColumn.HeaderStyle></DataGridTemplateColumn>

My requirement is that I need to put this <DataGridTemplateColumn.HeaderStyle> XAML markup section for every column at one place in <DataGrid.Resources> section. Everything is working fine except Foreground and Background properties binding in bold when I tried to put this  <DataGridTemplateColumn.HeaderStyle> in <DataGrid.Resources>. I have DatagridTemplateColumn and DataGridTextColumn in my Datagrid in XAML. Every column's display index is bind to different property like "Col1DispIdx","Col2DispIdx", "Col3DispIdx" etc...

So, please advise to achieve above functionality asap.

Regards,
Pratham

Parsing from string to int

$
0
0

in my C# project I have an array type of String. the array gets numbers from type int.

int numCell;
string[] arr = new string[numCell];

then i use it in a function like this:

sum += int.Parse(arr[i]);

and it works!

but, when i dothe same thing in WPF it tells me:

Input string was not in a correct format.

what shouuld i do?

Making an Array of Textblocks and displying on the screen when the app is running

$
0
0

Hello everyone

I am new to this UI development. I am making a reverse game model and I want show my

character array contents on text-blocks. I want to make an array of these text-blocks  and show them on screen

if there is another simple method please suggest me.

Getting the location of an element in the C# code.

$
0
0
How would I go about getting the coordinates of an element that is on a canvas? I'm needing to find these coordinates in the C# code.

Hybrid layout in WPF

$
0
0

Hello,

Please refer attached screenshot. This is how I want my layout in WPF. In this screenshot Green, Gray and Black boxes will be the user control added at runtime. Black box will be show/hide at runtime based on user operation.

As per my understanding using Grid with RowSpan and ColSpan for such layout will be difficult because I need to rearrange if any of the user control get removed or added or show hide at runtime. I also referred WrapPanel but it doesn't look suitable for this situation.

Kindly help me how can I achieve such layout? If possible please give some sample example/code to understand clearly.

Thanks,

Ayaz Shaikh


how many RelayCommand (DelegateCommand, FooWhateverCommand : ICommand) classes can I have in my WPF project?

$
0
0

Let's say I have several views, viewModel classes, Model classes in my project. Should I have just one RelayCommand : ICommand class with several overloaded constructors? Or should I have like RelayCommand1 : ICommand, RelayCommand2, .. to accommodate the various viewModels?


Rich P


[WPF] Show ComboBox or DatePicker according to the selected value in a combobox

$
0
0

Hi,
in my DataGrid:
1) in one column I have a ComboBox: item1, item2
2) in another column I would show a:
- a list if the user select item1 in the ComboBox 
- a datepicker if the user select item2 in the Combobox 

In XAML i have:

<!-- COLUMN 1 --><DataGridTemplateColumn Header="{StaticResource datagridScheduled}" SortMemberPath="Type.Description"><DataGridTemplateColumn.CellTemplate ><DataTemplate><TextBlock Name="dgScheduleType" Text="{Binding Type.Description, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  /></DataTemplate></DataGridTemplateColumn.CellTemplate><DataGridTemplateColumn.CellEditingTemplate><DataTemplate><ComboBox Name="dgCmbTypeOfSchedule"
					ItemsSource="{Binding Source={StaticResource DomainDataViewModel}, Path=SchedTypes}"
					SelectedItem="{Binding Type, Mode=TwoWay}"
					SelectedValue="{Binding Type.Description}"
					DisplayMemberPath="Description"
					SelectedValuePath="Description"></ComboBox></DataTemplate></DataGridTemplateColumn.CellEditingTemplate></DataGridTemplateColumn><!-- COLUMN 2 --><DataGridTemplateColumn Header="{StaticResource datagridDay}"><DataGridTemplateColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding Day, Mode=TwoWay}" /></DataTemplate></DataGridTemplateColumn.CellTemplate><DataGridTemplateColumn.CellEditingTemplate><DataTemplate><ComboBox Name="dgCmbDay" DataContext="{Binding}" SelectedItem="{Binding Day}"><ComboBox.ItemsSource><MultiBinding Converter="{StaticResource DateNumNameConverter}" ><MultiBinding.Bindings><Binding ElementName="dgPlan" Path="CurrentItem"/><Binding Source="{StaticResource AnalysisPlanViewModel}" Path="ListDayNameOfWeek"/>
<Binding Source="{StaticResource AnalysisPlanViewModel}" Path="ListDayNumOfMonth"/>        <Binding Path="Items"></Binding></MultiBinding.Bindings></MultiBinding></ComboBox.ItemsSource></ComboBox></DataTemplate></DataGridTemplateColumn.CellEditingTemplate></DataGridTemplateColumn>

In my Convert, I check the value select in dgCmbTypeOfSchedule and the convert returns one list or the other.
But, If I would that the convert returns a datepicker, it's possibile?

Thanks.

WPF Data gird double value in cell round up automatically

$
0
0

Hi All,

  I have one datagrid where one of the columns contains double values. I placed limitations on length and decimal part. Decimal part is always comes with 2 digits. Now during editing the cell that holds double value in DataGrid , if I enter value of 99.99 then it is becoming 100. At this moment the cell is still under edit mode.

 If the columns hold decimal type values then this automatic round up is not happening. But due to some constraints , at this moment we can't change the columns type from  double to decimal. So I just want to disable the auto round up with double values in DataGrid. I searched in MSDN forums but did not find any , tried adding StringFormat for columns. But it did not help.

I tested by keeping the double value outside of the DataGrid ( in editbox ) , I don't see any automatic round up. So I suspect there could be something with DataGrid that is resulting automatic round up.

Is there any way to disable this automatic round op on double values in DataGrid? I welcome your comment.

Thanks,

Brahmaji.

Be our next Spring WPF Guru!

$
0
0



In the northern hemisphere at least, Spring is here! (apparently)

And at TechNet Wiki, we're hoping you're all hatching new ideas for this month's TechNet Guru competition!

We're looking for more shoots and leaves of wisdom to sprout forth from the great tree of MSDN/TechNet life.

We're also hoping some of our old Guru winners will be coming back out of hibernation and flexing their grey matter!

So, pick up your pen and MARCH into TechNet History! This could truly be the start of something BEAUTIFUL!

What delightful new arrival will YOU be bringing into this world?

All you have to do is add an article to TechNet Wiki from your own specialist field. Something that fits into one of the categories listed on the submissions page. Copy in your own blog posts, a forum solution, a white paper, or just something you had to solve for your own day's work today.

Drop us some nifty knowledge, or superb snippets, and become MICROSOFT TECHNOLOGY GURU OF THE MONTH!

This is an official Microsoft TechNet recognition, where people such as yourselves can truly get noticed!

HOW TO WIN

1) Please copy over your Microsoft technical solutions and revelations toTechNet Wiki.

2) Add a link to it on THIS WIKI COMPETITION PAGE (so we know you've contributed)

3) Every month, we will highlight your contributions, and select a "Guru of the Month" in each technology.

If you win, we will sing your praises in blogs and forums, similar to the weekly contributor awards. Once "on our radar" and making your mark, you will probably be interviewed for your greatness, and maybe eventually even invited into other inner TechNet/MSDN circles!

Winning this award in your favoured technology will help us learn the active members in each community.

Feel free to ask any questions below.

More about TechNet Guru Awards

Thanks in advance!
Pete Laker



#PEJL
Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over toTechNet Wiki, for future generations to benefit from! You'll never get archived again, and you could win weekly awards!

Have you got what it takes o become this month's TechNet Technical Guru? Join a long list of well known community big hitters, show your knowledge and prowess in your favoured technologies!

Viewport3d contents invisible when started as a COM library

$
0
0

We have a .NET application, part of which uses a WPF Viewport3D using the .NET framework v4.

The .NET library is start from a legacy Delphi application using COM.

To rule out Delphi problems we created a simple test application in .Net. In the test application, when the application is displayed by creating an instance of the application the Viewport3D correctly displays its contents.

Dim Application AsNew StrikeAlpha.Application
Application.Show()

When the application is launched by the following code, much same way that Delphi would launch the application:

Dim alpha AsObject= CreateObject("StrikeAlpha.Application")
alpha.Show()

the visual contents of the Viewport3D is empty. We have concluded that the image is being correctly built as the contents are still hit-testable but they are not displayed on the screen to the user.

The problem also appears to be specific to this machine. It is a dedicated Windows Server 2008 R2 box hosted by 1and1 with remote web access setup and configured, so we cannot go to the physical server and rule out a remote desktop problem.

We do have the application successfully running on both an Azure Windows 2008R2 Virtual Machine as well as various other Windows Server 2008R2 servers throughout our customer base, which we can access using RDP for support and have not seen this problem on any other machine.

We’re now as confident as we can be that it is not a problem with our application code, it is running OK everywhere else, and that it is a confuragtion issue with this particular server, although we are at a point of not knowing what to check next.

Animation to the content

$
0
0

Hello 

In my WPF application, I have a TextBox which I use as search box.
Each time the user types a letter, I   displayed the result in a listbox.
I put the ListBox and a Label which allow me to display the number of matches in a Grid (with border).
Here are the codes.
TextBox

<TextBox Name="pbCompanyKeyword"       FontSize="13" Text=" Search Company..."   Margin="0"     BorderThickness="0"    Foreground="#FF747474"   GotFocus="pbCompanyKeyword_GotFocus" LostFocus="pbCompanyKeyword_LostFocus" TextChanged="pbCompanyKeyword_TextChanged" Padding="0,4,0,0"       ><TextBox.Resources><Style TargetType="{x:Type TextBox}"><Style.Triggers><Trigger Property="IsMouseOver" Value="true"><Setter   Property="Background"  Value="{StaticResource HoverBlackBtn}" /></Trigger><Trigger Property="IsMouseOver" Value="false"><Setter   Property="Background"  Value="#000" /></Trigger><Trigger Property="IsFocused" Value="true"><Setter   Property="Background"  Value="{StaticResource HoverBlackBtn}" /></Trigger></Style.Triggers></Style></TextBox.Resources></TextBox>



Result BOx

<Border x:Name="ResultList"    HorizontalAlignment="Left" Width="350" Background="#444444"  Margin="50,52,0,0" VerticalAlignment="Top"   ><Grid Margin="9,10,9,9"><Grid.RowDefinitions ><RowDefinition  Height="*" /><RowDefinition  Height="40" /></Grid.RowDefinitions><Grid  Grid.Row="0"    ><ListBox  x:Name="listFilter"    Margin="0" BorderThickness="0" BorderBrush="{x:Null}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Background="{x:Null}" HorizontalContentAlignment="Stretch" SelectionChanged="listFilter_SelectionChanged"  ><ListBox.ItemTemplate><DataTemplate><Border BorderBrush="#808080" x:Name="brd" Margin="0,0,0,0" BorderThickness="0,0,0,0" Padding="0,0,0,0"   HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  ><Grid><Border    BorderThickness="0,0,0,0" BorderBrush="#d3d3d3"     Grid.Row="1"     ><Grid><Grid.ColumnDefinitions><ColumnDefinition  Width="*"/><ColumnDefinition  Width="100"/></Grid.ColumnDefinitions><Grid Grid.Column="0"    ><TextBlock    Padding="9,5,5,5"  Text="{Binding CompanyName}" FontSize="13"   HorizontalAlignment="Left"  Foreground="{DynamicResource colorTitlebox}"    /></Grid><Grid Grid.Column="1"    ><TextBlock Padding="5,5,10,5" Text="{Binding Country}" FontSize="13" TextTrimming="CharacterEllipsis"   HorizontalAlignment="Right"  Foreground="{DynamicResource colorTitlebox}"     /></Grid></Grid></Border></Grid></Border></DataTemplate></ListBox.ItemTemplate></ListBox></Grid><Border  Grid.Row="1" BorderThickness="1"    BorderBrush="#595959" Background="#FF303030" VerticalAlignment="Top"    ><Grid><Label x:Name="lblRslt"       Content=""   Margin="0,0,0,5"     HorizontalAlignment="Left" Background="{x:Null}"   HorizontalContentAlignment="Left" Foreground="White" FontSize="13" FontFamily="Segoe UI Semibold"    /></Grid></Border></Grid></Border>



I have no difficulty to display the results.
I only display the first 10 results. So Listbox contains only 10 Elements up

 MyCustomFilter = new ObservableCollection<PublicCompaniesClass>(_mainWindow.myPbC.OrderBy(d => d.CompanyName).Where(d => d.CompanyName.ToLower().Contains(pbCompanyKeyword.Text.ToString().ToLower())).Take(10));


My difficult still in the animations.
What I want to do:

When the user starts typing.

I would like the size (height) of my "Resultlist" fits whatever the number of results that is displayed in the Listbox
I'm writing this code but no animation.

private void pbCompanyKeyword_TextChanged(object sender, TextChangedEventArgs e) { if (pbCompanyKeyword.Text != " Search Company..." && pbCompanyKeyword.Text != "") { MyCustomFilter = new ObservableCollection<PublicCompaniesClass>(_mainWindow.myPbC.OrderBy(d => d.CompanyName).Where(d => d.CompanyName.ToLower().Contains(pbCompanyKeyword.Text.ToString().ToLower())).Take(10)); listFilter.ItemsSource = MyCustomFilter; startSearch(); lblRslt.Content = MyCustomFilter.Count().ToString() + " result found "; if(MyCustomFilter.Count().ToString() == "0") { closeSearch(); } }

}


 private void startSearch()
        {
            if (ResultList.Height == 0)
            {

                 Storyboard myStoryboard2 = new Storyboard();
                myStoryboard2.FillBehavior = FillBehavior.Stop;
                DoubleAnimation animation2 = new DoubleAnimation();
                animation2.From = 0;
                animation2.To = ResultList.ActualHeight;

                animation2.Duration = TimeSpan.FromSeconds(0.9);
                animation2.FillBehavior = FillBehavior.HoldEnd;
                Storyboard.SetTarget(animation2, this.ResultList);
                Storyboard.SetTargetProperty(animation2, new PropertyPath("Height"));
                myStoryboard2.Children.Add(animation2);
                this.ResultList.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                myStoryboard2.Completed += (ss, ee) =>
                {
                    ResultList.Height = double.NaN;
                   this.ResultList.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;

                };
                myStoryboard2.Begin();


            }

        }
        private void closeSearch()
        {
            if (ResultList.Height != 0)
            {

              Storyboard myStoryboard2 = new Storyboard();
            myStoryboard2.FillBehavior = FillBehavior.Stop;
            DoubleAnimation animation2 = new DoubleAnimation();
            animation2.From = ResultList.ActualHeight;
            animation2.To = 40;
            animation2.Duration = TimeSpan.FromSeconds(0.5);
            animation2.FillBehavior = FillBehavior.HoldEnd;
            Storyboard.SetTarget(animation2, ResultList);
            Storyboard.SetTargetProperty(animation2, new PropertyPath("Height"));
            myStoryboard2.Children.Add(animation2);
            ResultList.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            myStoryboard2.Completed += (ss, ee) =>
            {
                ResultList.Height = 40;


            };
 myStoryboard2.Begin();


            }

        }


If no result is Locate, only the Label "lblRslt" should appear in the "Resultlist." if the textbox is empty. I close my "Resultlist."

How to anime "Resultlist" automatically whatever its  content.
Where is the error in my code?

Thnks

Viewing all 18858 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>