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

UserControl Arc Animation, Need complete cutomization of the Control

$
0
0

Hey,

I have done a small animation but I want this as a Control with full customization.

I mean should be able to change the color of stroke, count of arc, rotation speed, rotation angle, Tool tip message... and more

Please advise better way to do these stuffs.

<UserControl
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:System="clr-namespace:System;assembly=mscorlib" x:Class="AnimationLibrary.UserControl1" 
             mc:Ignorable="d" 
             d:DesignHeight="256" d:DesignWidth="256"><UserControl.Resources><System:Double x:Key="CenterAxis">128</System:Double></UserControl.Resources><Grid x:Name="grid"><Path x:Name="path" Width="{Binding ActualWidth, ElementName=grid, Mode=OneWay}" Height="{Binding ActualHeight, ElementName=grid, Mode=OneWay}"   Stroke="#FFF5087F"><Path.Data><GeometryGroup><PathGeometry><PathGeometry.Transform><TransformGroup><RotateTransform x:Name="Arc1" Angle="0" CenterX="{StaticResource CenterAxis}" CenterY="{StaticResource CenterAxis}" /></TransformGroup></PathGeometry.Transform><PathFigure StartPoint="128,0"><ArcSegment Size="1,1"   SweepDirection="Clockwise"><ArcSegment.Point><Point X="128" Y="256"/></ArcSegment.Point></ArcSegment></PathFigure></PathGeometry><PathGeometry><PathGeometry.Transform><TransformGroup><RotateTransform x:Name="Arc2" Angle="0" CenterX="{StaticResource CenterAxis}" CenterY="{StaticResource CenterAxis}" /></TransformGroup></PathGeometry.Transform><PathFigure StartPoint="128,64"><ArcSegment Size="1,1"   SweepDirection="Counterclockwise"><ArcSegment.Point><Point X="128" Y="192"/></ArcSegment.Point></ArcSegment></PathFigure></PathGeometry><PathGeometry><PathGeometry.Transform><TransformGroup><RotateTransform x:Name="Arc3" Angle="0" CenterX="{StaticResource CenterAxis}" CenterY="{StaticResource CenterAxis}" /></TransformGroup></PathGeometry.Transform><PathFigure StartPoint="32,128"><ArcSegment Size="1,1"   SweepDirection="Counterclockwise"><ArcSegment.Point><Point X="224" Y="128"/></ArcSegment.Point></ArcSegment></PathFigure></PathGeometry><PathGeometry><PathGeometry.Transform><TransformGroup><RotateTransform x:Name="Arc4" Angle="0" CenterX="{StaticResource CenterAxis}" CenterY="{StaticResource CenterAxis}" /></TransformGroup></PathGeometry.Transform><PathFigure StartPoint="160,128"><ArcSegment Size="1,1"   SweepDirection="Counterclockwise"><ArcSegment.Point><Point X="96" Y="128"/></ArcSegment.Point></ArcSegment></PathFigure></PathGeometry></GeometryGroup></Path.Data><Path.Triggers><EventTrigger RoutedEvent="FrameworkElement.Loaded"><BeginStoryboard><Storyboard><DoubleAnimation Storyboard.TargetName="Arc1" Storyboard.TargetProperty="Angle" From="-180" To="180" RepeatBehavior="Forever" Duration="0:0:2"/><DoubleAnimation Storyboard.TargetName="Arc2" Storyboard.TargetProperty="Angle" From="-180" To="180" RepeatBehavior="Forever" Duration="0:0:2"/><DoubleAnimation Storyboard.TargetName="Arc3" Storyboard.TargetProperty="Angle" From="180" To="-180" RepeatBehavior="Forever" Duration="0:0:2"/><DoubleAnimation Storyboard.TargetName="Arc4" Storyboard.TargetProperty="Angle" From="180" To="-180" RepeatBehavior="Forever" Duration="0:0:2"/></Storyboard></BeginStoryboard></EventTrigger></Path.Triggers></Path></Grid></UserControl>

Thanks

Jin


enjoy the life


Implement simple Controls.Primitives.Selector

$
0
0
Hello,

In WPF I fund class Controls.Primitives.Selector and I think I can use this class to implement simple Selector List. I try found in Internet information and example about this class but I nothing found. Do you know where I can found example how implement this class and how use IsSelected attachment property?

Best regards,
Grzegorz Wiśniewski

windows ecosystems suggestions

$
0
0

We believe the windows ecosystem is very much incomplete and not well organised, including its closest competitors ecosystems. Behind Software and hardware ecosystems is HUGE value, which we believe its time to move to the next phase in building it. We believe its not only up to MSFT employees to innovate an suggest ideas but its also a right to its developers and consumers, this not to criticise MSFT as the media does and fan boys, this to help improve what we developers also consider to be OUR platform and heavily invest our time, skills and finance in (MSFT used to say "you only stable as company when all your customer are happy" ). one advantage open source has is that developers have input in the development of the platform, MSFT can also add this by listening to its customers from all your products from servers to client, within this suggestions (using uservoice, which think is the best thing for a corporate like yours) are solutions to many problems you try an figure out (like any other company) and we thankful that you have started doing this, developers don't want to be constrained by too many features missing or not working properly this affects their business, so they often go for open source tools and products, why is it that amazon, facebook or google is not one of your biggest customers even though you sell such tools for such business models? Because of the constrains, feature list, flexibility etc. given by open source vs commercial, but its possible to achieve the same feature and flexibility with commercial tools too, by:

 1. Engaging with developers (and responding to their concerns) and

2. having a Developer Store that allows other developers who primary market is other developers, they sell developer applications and solutions to other developers within the windows ecosystem, e.g like a white label ecommerce platform, templates, Visual designs etc. This reduces cost of filling all niches and reduces constraints and it betters and increases the platforms capacity which allows any developer to build a thriving big business only on MSFT ecosystem because when you give developers a platform to help each other coupled with your efforts through MSDN it completes the ecosystem .

Instead of focusing completely on competition you need to asking your self "how do we optimise customer satisfaction and how to optimise our developers investment in our ecosystem over the short and long term?". The technique of having laud and media loved competitor can lead loosing focus on what matters to you and is important to you we recommend you remain focused.

 

Up until a business can thrive completely using your tools you will always have some new competitor not that they are in the same business but because they are showing the world including you customers that "to make it big like facebook, google, etc don't use MSFT tools or products" that's very bad for business and including developer businesses. The Ideal goals for any platform, products, services and tools business like yours is to allow any business to be wildly successful using MSFT tools, that should be your main objective, if your platform and tools are bad in comparison to other platform the developers switch. Your motto should be "MSFT the shuttle to the furthest star!" or something like that. Don't compete directly with your own developers, yes you can have a reference product within the industry but make sure you don't hurt their business too, compete and support them too.

 

Software ecosystems are an economies on their own, please treat and organise them as such. There is a colossal amount of value in this ecosystems not just financially, but on a user and developer point of view too, so please, take the effort of re-imagining the widows ecosystem as a whole, there are mathematical models(user, platform and developer exchange dynamics) you can use similar to general economics models to help optimise this ecosystem this where the future is going on business and developer perceptive.

 

Bundling an unorganised ineffective ecosystem creates problems on the client side including the developer side, this pushes the ecosystem to function inefficiently and threatens the entire ecosystem because the clients, developer and platform owners cant extract the optimal amount of value, leading to dissatisfied clients and therefore developer interest and revenue. Consumer apps can not be buddle with business apps, because they are fundamentally different in function and purpose, what is a stock or inventory management app be doing in windows store, or a music and video app be doing in an enterprise store.

 

To better, make more profitable and organise the ecosystems customer phasing front end we believe that each an very final client platform must have at list 3 stores, on top of that each client can be further be divided into consumer, home and business clients. Consumers are individuals, home clients are families and business are profit seeking groups that make other products. Each store must have a software store, hardware store and developer store. The software store will have software solutions that are relative that consumers, some of this software solutions are coupled with hardware on top of that a developer store is necessary to allow developers sell solutions to each other coupled with the efforts of MSDN, this give the ecosystem an edge on developer support and reduces cost and time for application deployment.

 

Some consumer apps are coupled as a complete solutions including their hardware e.g heart rate tracker and its app. For business most solutions come with their hardware too, custom detectors, sensors, servers, cables etc. Home user might have a security system and its app, home entertainment system hardware and its app, home air cleaning and conditioning hardware and its a app etc. we believe that the windows ecosystem must have a series of stores to cater for all its clients/consumers, help developers have clear target market and MSFT well organise its offering to wide variety of clients and developers that will directly affect satisfaction levels on the consumer side, and the developer finance side. This is how we think the ecosystem should be categorised:

 

Windows store (on desktop, tablet, phone, xbox, TV etc)-1. A. consumer app store 1.B. Consumer hardware store. 1.C . Consumer apps developer store

2.A. Home app store. 2.B. Home hardware store. 2.C. Home app developer store

3.A Business app store. 3.B Business hardware store. 3.C Business app developer store

4.A. Add-on application store (e.g Office, sharepoint, outlook, adobe, matlab, etc) 4.C add-on developer store

 

The above makes things vary clear to the clients, consumers and the platform owner and makes it easier to do business and it can also be applied to Windows Azure too.

 

1. For the consumer  stores: A.  App revenue is shared with MSFT and developers B. A Microsoft Store App (like the website) selling consumer PC and accessories (PC, printer, RAM, Monitors, mice etc), some might have a relating app on the software store others wont, using a drop shipping method this method is easy to implement, revenue is on commission for MSFT from OEMs. C. There are some products that not meant for consumers but help or aid in the development of consumers software such as codes, templates, tutorials, software books, UI elements, back end Software as a service, Platform as a service, Infrastructure as a service, e-commerce back-end .etc so its necessary to consolidate this products in to one listing directory, developer pay a monthly fee to list. This also helps and aids with the developers marketing gaols. And eases MSFT's resources to help and aid developer through MSDN, MSFT is giving developers the opportunity to help and aid each other too.

 

2. For the Home stores: A. App revenue is shared with MSFT and developers or OEMS, most here are free since its part of complete home solution. B. A Microsoft Store like App but focusing on home hardware, like home entertainment system hardware, security system, air conditioning systems, air cleaning systems hardware, energy management systems hardware etc. kids monitoring hardware etc. using a drop shipping method this method is easy to implement, revenue is on commission for MSFT from OEMs. A directory for a local human installer and maintenance will be necessary in most cases. The user buys then a MSFT local partner installs and maintenance the system, this expands the ecosystem for MSFT ISV too. C. Same as 1.C above.

 

3. For the business stores A. Seller can just pay a monthly listing fee on the app store. B. Business hardware companies can also list their the products on monthly fee here too. C. Developers selling to other developers can also list for a fee here too same as 1.C above. Please note this stores consist a lot custom ERP products and services for small and large businesses (Dynamics, Oracle, SAP etc) so its better just to list their products and services. This very beneficial since it consolidates all the products and services that are relative to the windows ecosystem.

 

4.for add-on software. Application like Office, adobe packages, ERP packages have non standalone software that needs the main software package so its necessary to have this in one place than each software package having their own separate store, this also reduces cost to run their store etc.

 

We also believe you should increase the number of ways to buy apps from the windows app store not just credit cards (international credit cad holder population is significantly lower than the number of users that buy and use PC's world wide, and top of that in some countries interest rate are so high that credit cards are discouraged), include buying and subscribing to apps using Microsoft points, cell phone network carrier billing, coupons (which can be sold by other vendors in local areas) etc in all cases increasing purchasing options increases app purchases and subscriptions by 70%, so please consider this very closely its important to the ecosystem and its developers world wide we know that you have done this on the windows phone platform but users want it on windows 8 too.

 

With bing.com/aps we believe you should have a paid premium version too, directed to business, governments and individuals that allows access to other databases like Market research papers, Academic/business journals, ebooks, research papers/publications, old scanned news papers/magazines and books that where never digitized etc, the primary objective here is to have a search engine that gives access to all the information/data that has ever been written by man-kind the value of such a product is long term and indispensible since information is a valued commodity on its own (as long people and business exists they will need information and data but how this is perceived or analysis depends on them. Windows developers can also subscribe to this information and data and use it to develop analytical solutions to theirs customers too and bing can also have its analytic services too, including Excel and its app store) that's why search engines are a big business, but using a ad supported model will restrict adding more value and the growing business. An analytic bing AI can be part of the paid premium bing, including a store for research papers or a listing for research companies. Information is a big deal, with out it many institutions or people make wrong decisions, with it they feel more empowered and make better confident decisions, making our world and economies better, example : the credit crunch could have been avoided if investors knew or foresaw the credit bubble. Please understand the present value and future value of information and data then you realise that its been undervalued for a long time and going into it will offer good returns to both MSFT and its developers, please note that you don't have to be the source of it (like msn.com) but the extractor, keeper and analyser of it but can own control strategic information or data as mentioned above for competitive advantage and allow developers access the data through you to create custom solutions to their cusdtomers.

 

Add uservoice.com for windows and other services, make sure you respond promptly and adequately nothing frustrates customers and developers more when they give feedback and they get a terrible response, which indirectly defeats the purpose increase customer service.

 

Have PC finance, maintenance and insurance plan where users pay say $X.XX per month over 3 years and they get a PC and a phone, maintenance services, software licences (Office and other of their choice in windows store) and a PC insurance plan. This can be sold purely through ISP's, ISV's and other 3rd party retailers or directly from Microsoft stores. This is very much the same as car finance plan, only that its for Personal computers, if the automobile industry can do this on a global scale including very remote regions in the world why cant computer companies too. Please note that also reduces piracy and betters your relationship with consumers and adds more value to the relationship because of better customer care, and  increases developers confidence in the ecosystem. We also think that you should use a franchise model for your Microsoft stores, to better distribution like KFC, BMW motor and others. This model costs less to start and run and allows faster deployment of store if you couple this with the above mentioned finance, maintenance and insurance plan it betters the ecosystem in a big way. At the moment there are a lot distribution companies that distribute PC's and PC accessories to avoid friction communicate with them before hand and give them 1st priority of the franchise deployment.

 

 

MSFT marketing is not good enough, instead showing off features and user benefits, you over do the inspiration technique that's used a lot by motor industry except a few others. You have to sell the product by explaining its functionality, show off how the user benefits from the product then add inspirational theme this allows the viewer to be objective when weighing their options versus competitor products, it allows them to see and understand the value of the product in their personal lives or business. But above all things the product has to be truly beneficial relative to the advertisement(one thing that you not taken advantage of is your fan base, you notice them a lot if negative MSFT article is written on the internet in the comment section, or through dedicated windows websites and blog if you utilise this to optimal levels including their followers on social sites you draw a lot more users and grow the ecosystem. Andriod OS did not grow mainly because it was a better product alone, but because it had a huge fan base too and we are sure google did not spend much on marketing in this case, so you have to grow your user base by maybe including an affiliate commission marketing engine into the microsoft store and windows stores, give away promotional products to your Fan base, on top of that you need a dedicated chief of marketing not hybrid financial and marketing chief as you have now make that into two departments not one, these two are different department in many companies and academic spheres you need a dedicated marketing officer etc). Technology companies are getting lost in providing solutions to societies, they focus on the wrong things(how does consumer benefit from a self driving car, or internet connected blanket etc), products have to be truly beneficial to the user, instead they spend billions on R&D on new technologies rather than also spend time on figuring out how to solve today's problems with new products that use today's technology, the iphone did not have anything technologically beyond current technology, they solve the problem of making great phones by using technology that already exists not to say that you should do research but also use try and figure out how to create products from existing technology, the technology might need refinement but it will cost less time and money to produce this great for consumers and your developers. From a business perceptive any company in the world would buy any product that will directly or indirectly influence their profitability(direct influence :increase sales etc. Indirect influene: increase production, better customer service, operation efficiency, cost reduction, etc) that's the main criteria you need to evaluate before shipping or investing in an idea that's meant for business, in some cases the influence on profitability is not very clear. The reason advertising products or platforms make a lot money is because they have the ability to influence sales directly, like google advertising products. This helps the ecosystem and its developers.

 

Essential apps on consumer products: 1. banking apps (in every country that windows 8/ windows phone is sold make sure you have  banking app, if this might prove to be expensive the make them to subscription dependent paid by the bank since you developed it integrated with the wallet app, you can also allow banks to integrate with the OS as if one unit to better the experience) 2. Health apps platform, similar to what you are trying to do with health vault, make sure it integrate with each countries health department infrastructure, a subscription version will cover cost too. 3. other financial services apps, such investments, advisory etc each country paid the as subscription etc. 4. other personal support services. This model came from the days where each family had a family doctor, lawyer, financial advisor, insurance, etc this services are considered to be essential services for every family or individual, if you could build a back end platform to this platform to allow those that offer this kind services to be offer using this platform it will be big deal and make the platform more personal since it will be on their personal devices.

 

Interactive Radio/TV Applications: develop a platform/software as a service on Azure for the Radio/TV industry. The user phone/PC needs a hybrid radio/TV frequency antenna (FM/AM/UHS) and internet antenna and an template application from the radio station. This configuration will allow interactive radio/TV for the user, the sound or audio or video is sent through radio/TV waves into the application and the interaction (comments, etc) will be done of the internet using some new Skype comment system also when a radio advertisement plays the user will see the advertisement (picture or video )on their phone/PC application which allows them to interact with the advertisements but clicking through to the website and buy the product, this can also be part of bing Ads so advertisers can now also advertise on Radio/TV coupled with the internet this increases exposure and therefore ROI, you can call this Xbox Radio/TV or something. The Idea here is that LIVE data is transported using Radio/TV frequencies and user interactions (comments, click through to website etc) done over the internet. All you do is build a back end structure on Azure and offer (free or subscription) this to the TV/Radio industry as service globally, they then design the front end based on the temples you give them and API's to suite their brand but must be at little cost meaning many things should come prebuilt to increase adoption rates, but you also have to communicate with you OEM to include this two antennas/receivers built in. the application can play on any platform (windows, apple, linux etc ) that supports the hybrid data transmission for live TV/Radio and internet. Then figure out how bing ads/adcenter can advertise on the platform. This the future of media application, that allows a live a feed and a low latency interactions.

 

Find a way to licence Xbox to TV makers so that they build the Xbox within their TV sets but also build a back end infrastructure (Paas/Saas) so they also can deliver their own services to differentiate for their brand against their competition. Massive customization capabilities including rebranding the OS is very important when it comes to brand awareness, this very applicable to your OEM,s. You see this lack of enthusiasm from their product idea, the windows OS creates constraints, you have allow allot flexibilities so that they are able to differentiate for their brand and get to own their final product this give them pride and a better marketing push for the platform, but in all those cases the back end should allow cross platform programming despite the type of windows OS on that OEM.

 

We also suggest Outlook and skype apps should be one product based on the fact that they are both communication products, one for text and images, one for text, images and video, we think you wasting resources because of this overlap, transport outlook to skype so you have one-all-in-one communication application this also applicable to Lync. You wasting you own resources and also confusing your customers and your developers.

 

We suggest that you have internet explorer and Bing apps on ios, OSX, linux distributions, blackberry, ubuntu, firefox OS etc. the reason behind this is to expand your services, right now according to Goldman Sachs, you have 20-30% market share in all internet connected devices (phone, tablets, desktops, TV's etc), that means that all your internet efforts are targeting less 20-30% (maybe 10%) off all internet connected devices. Look at google and facebook they don't discriminate against other platforms this allows them to make billions of dollars. For internet services to grow and allow ASP.net community to grow you have Bing Apps and internet Explorer on other platforms just like skype.

 

Even with this changes the windows ecosystem will still be prone to competition strategies, to seal its position, the only way to do this is have an solid physical network that delivers data to and from clients devices and network, even though the internet exists the client still needs to pay the ISP to transport the data, for MSFT to build a complete ecosystem it must building its own or acquirer one, building one is very expensive and will take too long, acquiring one can be cheaper if MSFT focuses directly towards low orbit satellite internet, it makes easier to reach a full global audience rather the build terrestrial hubs on earth, using Low Earth Orbit (LEO)satellite constellations can and will can also reduce latencies too, and allow home and business clients to draw directly access the ecosystem and the public internet with a mounted satellite dish (two way and single way transmissions), MSFT best shot to this is ready made LEO by Iridium inc (all your products and services depend on a data transmissions provider, which affects user side cost, satisfaction and ISP power, a hybrid two-way and single way dish can finally complete the platform reach into every home in the globe, that's like 4 billion + potential customers), you can call yours Skype Communications inc or something. Google is also ahead with its Google fibre, which its getting ready to offer for free in the exchange who ever implement it must use Google services with it(this allows them to be the middle man on everything that bought globally that translates to 100s of Billions dollars in future), they have already have Dish TV partnership, in some cases they might not see it the value in some cases they do, but when they do they act.

 

We believe that you have also gone off the wring direction and lost identity due to competition pressure or media coverage, what ever they do or say you should not affect what you do, you guys need act on your intuition. We believe that your efforts to being a device and services company will draw you away from being a platform and tools company which allows to tap a huge amount developer investment and resources than developing a few devices and services here and there on your own, we prefer you be a tech platform, tools and services company and rather making your own branded hardware, design white label products which will allow you to be as profitable and flexible as possible in future when the market changes and new entrants come and go. Software tools for productivity have high initia that entertainment products, which allows you more time to adapt to new changes in future, whereas branded client consumer devices come and go every 3 to 4 years. Creating a back end physical infrastructure (LEO, Iridium inc) as mentioned above will solidify future existence and forced changes, and allow developers to further invest in the platform and solidify revenue for developers and therefore MSFT over a longer term.

 

As long as the value-to-price ratio is high you win, and its developers continue to develop for making even more better.

 

Activate WPF Window without losing focus on previous opened application/window

$
0
0

I had a WPF window in application which I Activate on some specific scenarios by calling 

MainView.Activate();

and 

MainView.BringIntoView();

 method. it also sets focus on this 'MainView' window.

But my requirement was this window shouldn't getFocus. i.e. my cursor should still remain on previous application(notepad,word etc..)

I tried using MainView.ShowActivated="False" but it didn't work.

then after some help from This link I did following code :

IntPtr HWND_TOPMOST = new IntPtr(-1);
            const short SWP_NOMOVE = 0X2;
            const short SWP_NOSIZE = 1;
            const short SWP_NOZORDER = 0X4;
            const int SWP_SHOWWINDOW = 0x0040;

            Process[] processes = Process.GetProcesses(".");

            foreach (var process in processes)
            {
                IntPtr handle = process.MainWindowHandle;
                if (handle != IntPtr.Zero)
                {
                    SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
                }
            }

But this only works if My window is minimized andnot working if window is WindowState.Normal and is hiding behind some app(IE etc..). what to do?

thanks in advance


Dheeraj

How to prevent TabControl from doing multi rows?

How to calculate totals of wpf datagrid column with dataset which is created by adding a DataTemplate in Resources?

$
0
0

I am trying to figure out what is the best way to calculate a total value of DataGrid column in wpf, I´m using dataset to display data from SQL server in my Resources(DataTemplate) & bind it to datagrid like below:

DataTemplate:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    x:Class="AgamistaStore.Resources.DataTemplatesClass"
                     xmlns:myClasses="clr-namespace:AgamistaStore.Classes"><myClasses:TablesStateConverter  x:Key="TablesStateConverter"/><myClasses:OrderItemNotEditableStateConverter x:Key="NotEditableStateConverter"/><!-- ProductName column --><DataTemplate x:Key="NotEditableStateColumnTemplate"><Image Height="20" Width="20" Source="{Binding Path=NotEditable, 
                Converter={StaticResource NotEditableStateConverter}, Mode=Default}" HorizontalAlignment="Stretch"/></DataTemplate><!-- Barcode column --><DataTemplate x:Key="ProductBarcodeColumnTemplate"><TextBlock  FontFamily="Tahoma" FontSize="14" Text="{Binding Path=ProductBarcode}" HorizontalAlignment="Stretch"
                    Foreground="#FF44544A" /></DataTemplate><!-- ProductName column --><DataTemplate x:Key="ProdNameColumnTemplate"><TextBlock  FontFamily="Tahoma" FontSize="14" Text="{Binding Path=ProductName}" HorizontalAlignment="Stretch"
                    Foreground="#FF44544A"/></DataTemplate><!-- Price column --><DataTemplate x:Key="PriceNameColumnTemplate"><TextBlock x:Name="SalePrice" FontFamily="Tahoma" FontSize="14" HorizontalAlignment="Stretch" 
                   Text="{Binding Path=SalePrice, StringFormat={}{0:#.##}}" Foreground="#FF44544A"/></DataTemplate><!-- Quntity column --><DataTemplate x:Key="QuntityColumnTemplate"><TextBox x:Name="txtQuntity" Tag="{Binding}" PreviewTextInput="txtQuntity_PreviewTextInput" 
                      Style="{StaticResource TextBoxStyle}" Height="20"  Foreground="#FF0A421F" 
                     FontFamily="Tahoma" FontSize="14"  Text="{Binding Path=SoldQuantity}" HorizontalAlignment="Stretch"/></DataTemplate></ResourceDictionary>

MainWindow:

<Border Grid.Column="1" CornerRadius="6,6,6,6" BorderThickness="1,1,1,1" BorderBrush="#FFBCC7BB" 
                        Margin="9,10,8,10" x:Name="borderDetails"><Grid HorizontalAlignment="Left" Width="439" Margin="0,0,0,0" VerticalAlignment="Top" 
                      Height="397" Visibility="Visible"><Grid.RowDefinitions><RowDefinition Height="352*" /><RowDefinition Height="45*" /></Grid.RowDefinitions><!--bill details --><myClasses:SortableListView Margin="9,6,6,0" Height="auto" BorderBrush="{x:Null}"
			                      Background="{x:Null}"   ScrollViewer.VerticalScrollBarVisibility="Auto"
			                      ScrollViewer.HorizontalScrollBarVisibility="Auto" AllowDrop="True" 
			                      VirtualizingStackPanel.IsVirtualizing="True" ScrollViewer.CanContentScroll="True"
			                      SelectionMode="Single"  IsSynchronizedWithCurrentItem="True"
			                      ItemContainerStyle="{DynamicResource RestaurantEditListViewItemStyle}"
			                      Style="{DynamicResource RestaurantEditListViewStyle}" IsEnabled="True" 
                                  HorizontalAlignment="Stretch" VerticalAlignment="Top" x:Name="gvOrderDetails" ><myClasses:SortableListView.View><GridView AllowsColumnReorder="False" ><GridViewColumn Width="4" 
                                           HeaderContainerStyle="{DynamicResource FirstColumnGridViewColumnHeader}" 
                                           CellTemplate="{StaticResource EmptyColumnTemplate}"/><GridViewColumn Width="8" CellTemplate="{StaticResource NotEditableStateColumnTemplate}" 
                                        HeaderContainerStyle="{DynamicResource RestaurantDataGridViewColumnHeader}"/><myClasses:SortListViewColumn Header="كود الصنف" SortProperty="ProductBarcode" 
                                         Width="80" CellTemplate="{StaticResource ProductBarcodeColumnTemplate}"  
                                         SortStyle="RestaurantDataGridViewColumnHeader" 
                                         HeaderContainerStyle="{DynamicResource RestaurantDataGridViewColumnHeader}" /><myClasses:SortListViewColumn Header="اسـم الـصـنـف" SortProperty="ProductName" 
                                         Width="200" CellTemplate="{StaticResource ProdNameColumnTemplate}"  
                                         SortStyle="RestaurantDataGridViewColumnHeader" 
                                         HeaderContainerStyle="{DynamicResource RestaurantDataGridViewColumnHeader}" /><myClasses:SortListViewColumn Header="السعر"  SortProperty="SalePrice"
                                         CellTemplate="{StaticResource PriceNameColumnTemplate}" 
                                         Width="60" SortStyle="RestaurantDataGridViewColumnHeader" 
                                         HeaderContainerStyle="{DynamicResource RestaurantDataGridViewColumnHeader}" /><myClasses:SortListViewColumn Header="الكمية"  SortProperty="UnitName" Width="50" 
                                         CellTemplate="{StaticResource QuntityColumnTemplate}" 
                                         SortStyle="RestaurantDataGridViewColumnHeader" 
                                         HeaderContainerStyle="{DynamicResource RestaurantDataGridViewColumnHeader}"/><GridViewColumn Width="4" CellTemplate="{StaticResource EmptyColumnTemplate}" 
                                         HeaderContainerStyle="{DynamicResource LastColumnGridViewColumnHeader}"/></GridView></myClasses:SortableListView.View></myClasses:SortableListView>

Now I want to get the total sum (which is sum(SalePrice*SoldQuantity)  to display in textbox, And SoldQuantity value can changed by user

What is the best practice to do this ?

Thanks,



UpdateSourceTrigger=PropertyChanged causing exception during InitializeComponent() on WP7

$
0
0

I have a simple page with just one TextBox control whose Text is bound to a property in my ViewModel. When I use UpdateSourceTrigger=Default, everything is fine, however, when I use UpdateSourceTrigger=PropertyChanged, I get an exception

{Failed to create a 'System.Windows.Data.UpdateSourceTrigger' from the text 'PropertyChanged'.}

When I click on the details of the exception, I get

{"You can only use State between OnNavigatedTo and OnNavigatedFrom"}

I am suspecting that this is because I set the DataContext for the binding in the NavigatedTo() function that is called AFTER the InitializeComponent() where the exception is thrown.

Any suggestions on how to get around this -- I really need the PropertyChanged trigger behavior.

Thanks.

Here are the 2 functions and XAML code for completeness:

public AddNewPlayerPage()
{
    InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    if (_viewModel == null)
    {
        _viewModel = PhoneApplicationService.Current.State["ChooseItemVM"] as ChooseItemVM;
        DataContext = _viewModel;
    }
}
<TextBox Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>


Where to place child control event handler logic in MVVM ?

$
0
0

Hi Experts,

Im new to WPF and so MVVM.

I have created a user control with a DataGrid and im invoking this user control from another WPF form and within that main form i'm setting the data context and grid in the child (user control) populates correctly. what i need is,

I have attached attributes to the binding collection which holds the actual column header text

ex : 

[HeaderName("Email Address")]
public string Email { get; set; }

using reflection I should iterate through the property attributes and get the actual header name and customize the grid. 

this can be easily done within datagrid's ColumnGenerated event handler. But my problem is where this logic should go in in a MVVM application ? if this logic should go to some other class how can i place datagrid's ColumnGenerated event in another class ?

appreciate your help on this. 


Autosize Menu

$
0
0

Hi,

I have a menu, oriented vertical. This menu is in a grid and I want this menu to adjust its height automatically to the window size. Any suggestions are appreciated.

Thanks

How can I change a labels text when SD Card is removed

$
0
0

I am creating a utility that changes settings for a LED Light using a SD Card. Now, I have it working perfectly fine on Windows 8 (I used Windows 8 to make it), but when I test it on Windows 7 the label doesn't change to "SD Card Not Inserted" when the card is removed during run-time. 

I have used a dispatchTimer to check if the card is removed/inserted and if it is then the Label reads "SD Card is Available" and if it isn't then it should read "SD Card Not Available". Does anyone know how to work this? Maybe it is something to do with the Array that I have used:

 private void dispatcherTimer_Tick(object sender, EventArgs e)
        {

            string[] drives = Environment.GetLogicalDrives();
            foreach (string drive in drives)
            {
                
                try
                {

                    DriveInfo di = new DriveInfo(drive);
                    if (di.VolumeLabel.Contains("STAR-LIGHT"))
                    {
                        var bc = new BrushConverter();
                        sdAvailability.Foreground = (Brush)bc.ConvertFrom("#FF83A680");
                        updateBtn.IsEnabled = true;
                        sdAvailability.Content = "SD Card is Available";
                    }
                }
                catch { }

                try
                {

                    DriveInfo di = new DriveInfo(drive);
                    if (di.VolumeLabel != "STAR-LIGHT")
                    {

                        var bc = new BrushConverter();
                        sdavailability.foreground = (brush)bc.convertfrom("#ffa45f5f");

                        sdavailability.content = "sd card not available";
                        updatebtn.isenabled = false;

                    }
                }
                catch { }
            }
        }

Could anyone please help me out, if you need any more information please ask.

Thanks in advance.

Lee.

WPF Custom Control Display only part of hierarchical structure

$
0
0

Hi Guys, 
at the moment I am working on a custom control that allows the user to navigate through levels of hierarchical data. 
Data example: 
Node 1
        Node 1.1 
        Node1.2
                Node1.2.1
                Node1.2.2
Node 2 
Node 3 
        Node3.1
        Node3.2
Node 4
The control always displays the current level of data, for example all children of Node3 (3.1 and 3.2). The User should be able to navigate through the hierarchical data by clicking on an item or pressing a back-button.  The problem with that is that I don´t know the class type of the view model objects so I don´t know which property contains the child nodes of each node. As I need to access their child nodes for navigation I can´t use binding in a data template because the related items aren’t yet created (as they are displayed in a list, not a tree!). 

Any ideas on how to solve this problem elegantly? 


ListBox DataTemplate - Displaying Image/Not displaying Image

$
0
0

Hi,

I am using a list box with the following data template and I am filling the item list from my messageitem class which contains the message and the path to an image. 

The problem I have is that the image is a correct mark which is displayed when a task completes. Prior to the task completing I am updating a single object in the listbox to displaying waiting.... ( like this )

waiting.

waiting..

waiting...

waiting... etc

Because at this point, I am passing in a bogus path to an image, my app throws out an exception each time on the output console due to the fact it can not find the image. Is there any way, i can have the image as an optional member or do something a little tidier? 

thanks,

ro

<ListBox IsHitTestVisible="False" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.CanContentScroll="True" BorderThickness="0" Background="Transparent" Name="lstCheckCardMessages" FlowDirection="LeftToRight" SelectionMode="Single"><ListBox.ItemTemplate><DataTemplate><StackPanel><StackPanel Orientation="Horizontal"><TextBlock Text="{Binding Path=Message}" Width="250" Padding="5" FontSize="16" Foreground="Black"></TextBlock><Image Source="{Binding Path=Imagesource}" Height="50"/></StackPanel></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox>

DataGrid gets locked on ValidationError

$
0
0

Hi,

 I am using a simple a ValidationRule on DatagridTextColumn. The Validation occurs properly so no issues there. If ValidationError occurs, then the whole DataGrid is locked (and that seems reasonable). The problem occurs when the row for which validation failed is removed from the DataGrid. The row in error gets removed, but somehow the other DataGrid rows still remains in a Locked(non editable) state even if there aren't any more rows failing the validation. Any ideas why DataGrid rows still remain locked. Here is relevant code for the DataGridTextColumn.

<DataGridTextColumn <DataGridTextColumn.Binding><Binding Path="Name" NotifyOnValidationError="True"
                 UpdateSourceTrigger="LostFocus"><Binding.ValidationRules><local:SomeValidationRule/></Binding.ValidationRules></Binding></DataGridTextColumn.Binding></DataGridTextColumn>


regards,

Nirvan.

 

WPF Fixed Document Problem

$
0
0

I have a Problem With Fixed Documents  I Want My Client

To be able To Enter His Customers  ID So That He Can Retrieve

They Monthly Payment And So on but the Fixed Documents

Only can run One query,  as I enter The second  Customer ‘s

ID I get an Error                {"Specified Visual is already a child of another Visual or the root of a CompositionTarget."}               System.Exception {System.ArgumentException}

The  Code Create a Grid And  Fills It With All Required Data and Then Runs The Following

Statement 

   FixedPage clientFixedPage = new FixedPage();               Grid clientGrid = new Grid();        RowDefinition clientRow;        ColumnDefinition clientColumn;              PageContent clientPage = new PageContent();

   //Output Reports Results  In Fixed Document

                       // if (clientPage .Child==null )

                       // {

                clientGrid.Width = this.clientAccountFixedDocument.DocumentPaginator.PageSize.Width;

clientGrid.Height = this.clientAccountFixedDocument.DocumentPaginator.PageSize.Height

clientFixedPage.Children.Add(clientGrid);

((System.Windows.Markup.IAddChild)clientPage).AddChild(clientFixedPage);

 this.clientAccountFixedDocument.Pages.Add(clientPage);

                       // }

                        //else if (clientPage .Child !=null )

                       // {

                           // clientFixedPage.Children.Clear();

                         //   clientFixedPage = new FixedPage();

                            //clientPage.Child.Children.Clear();

                           //clientFixedPage.Children.Add(clientGrid);

                           // ((System.Windows.Markup.IAddChild)clientPage).AddChild(clientFixedPage);

                           // this.clientAccountFixedDocument.Pages.Add(clientPage);

                      //  }

                        

The XAML Locks Like This

<DocumentViewer  VerticalAlignment="Top"  Grid.Column="0"
         Grid.Row="2"    x:Name="clientAccountDocumentViewer" HorizontalAlignment="Stretch" Width="auto"    DataContext="{Binding}" >
            <FixedDocument x:Name="clientAccountFixedDocument" />                         
        </DocumentViewer>
The Control That Run Customers ID Lock Like This

 private void accIdTxt_KeyDown(object sender, KeyEventArgs e)
        {
            rentalClientAccount = new RentalClientAccount();
            int rowCounter = 0;
            if (e.Key == Key.Enter){
 if (accIdTxt.Text.Length > 0 & yearTxt.Text.Length > 0){
               foreach (EstateSerializer clientAccountItems in
 rentalClientAccount.GetClientPaymentByAccountID(this.accIdTxt.Text, int.Parse(yearTxt.Text)))
                        {
    


Help with binding to parent property on a style

$
0
0

Hi,

I'm trying to set up a textblock style such that if text is empty, the textblock displays some default information.

I'm currently having some trouble setting up RelativeSource, as I understand it and have seen elsewhere. I've tried a number of solutions found on forums, but no luck as of yet.

<TextBlock Grid.Row="5"
                                   Name="test"
                                   TextWrapping="Wrap"
                                   Text="{Binding Context}"><TextBlock.Style><Style BasedOn="{StaticResource labelTextBlockStyle}" TargetType="TextBlock"><Style.Triggers><!-- Can't re-bind to text propery since it would cause an infinite loop--><DataTrigger Binding="{Binding Text.Length, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TextBlock}}}" Value='0'><Setter Property="Background"><Setter.Value><VisualBrush Stretch="None"
                                                                 AlignmentX="Left"
                                                                 AlignmentY="Center"><VisualBrush.Visual><TextBlock Text="None"
                                                                       FontStyle="Italic"
                                                                       Foreground="DarkGray"></TextBlock></VisualBrush.Visual></VisualBrush></Setter.Value></Setter></DataTrigger></Style.Triggers></Style></TextBlock.Style></TextBlock>

When I use ElementName=test, it works as I expect it to. However, when I use the RelativeSource it never applies the DataTrigger. (The VisualBrush never appears.)

I'd like to keep it with some relative binding, as I would like to actually apply this style to several TextBlocks.

What am I doing wrong?

Thanks!



Custom Progressbar with image

$
0
0

Hey guys,

I would like to create a custom progressbar with an image. I have an image where the transparant part must be "filled" with a color until the "job" is done. When the job is done the image must be filled to the top :)

Can someone point me out the right direction ?

thanks !

MVVM - WPF Button using command delegation is giving inconsistent click behavior

$
0
0

I have a composite button control built up as a styled Button containing a StackPanel containing an Image and a TextBlock.  The issue I am having is that actually clicking the button at runtime is surprisingly difficult and giving inconsistent behaviors.  If I mouse over the button and the hover style takes effect (changes background color of button) the button is unclickable.  If I minimize my window and maximize then "sneak in from below" I can click the button as long as I haven't moused over far enough for the style to take hold. 

Here is my xaml:

<Button Command="{Binding ButtonClickedCommand}" CommandParameter="ManageCustomers" Style="{DynamicResource MyToolBarMenuButtonStyle}"><Button.ContextMenu><ContextMenu><MenuItem Header="New Customer" Command="{Binding ButtonClickedCommand}" CommandParameter="NewCustomer"/><MenuItem Header="Customer Notifications" Command="{Binding Path=CustomerNotificationsCommand}"/></ContextMenu></Button.ContextMenu><StackPanel Orientation="Horizontal"><Image Source="/OurProject.Resources;component/Graphics/ppl.ico"/><TextBlock Margin="3,0,0,0">Manage Customers</TextBlock></StackPanel></Button>

When I wire this up differently using click events in the code behind that delegate to an ICommand in the ViewModel, the style is applied consistently and there are no button anomolies such as I described above. 

What gives?

[edit]

inside the ViewModel(CanExecuteButtonClicked simply returns true):

public OurToolbarViewModel(IEventService eventService) { EventService = eventService; ButtonClickedCommand = new DelegateCommand<object>(HandleButtonClicked, CanExecuteButtonClicked); } public ICommand ButtonClickedCommand { get; private set; } private void HandleButtonClicked(object args) { EventService.GetEvent<ViewChangeEvent>().Publish(args as string); }

 

The Style's Template:

<Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type Button}"><Border SnapsToDevicePixels="True" x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" ContextMenu="{TemplateBinding ContextMenu}" ><Grid Width="Auto" Height="Auto" x:Name="Grid"><Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions><Button Grid.Column="0"  Content="{TemplateBinding Content}" Style="{DynamicResource MyToolBarButtonStyle}" Background="{x:Null}" BorderBrush="{x:Null}" BorderThickness="0.7,0.7,0.7,0.7" Padding="3" /><Button x:Name="triangleButton" Grid.Column="1" BorderThickness="0.7,0,0,0" Style="{DynamicResource MyTriangleButtonStyle}" Background="#00DE2424" BorderBrush="{x:Null}" Padding="0,0,0,0" Click="triangleButton_Click" /></Grid></Border><ControlTemplate.Triggers><MultiTrigger><MultiTrigger.Conditions><Condition Property="IsMouseOver" Value="True"/><Condition Property="IsFocused" Value="False"/></MultiTrigger.Conditions><Setter Property="Background" TargetName="Bd" Value="{DynamicResource MyMouseOverOrangeGradientBrush3}"/><Setter Property="BorderBrush" TargetName="Bd" Value="{DynamicResource MyDarkOrangeSolidBrush}"/><Setter Property="BorderBrush" TargetName="triangleButton" Value="{DynamicResource MyDarkOrangeSolidBrush}"/></MultiTrigger><Trigger Property="IsEnabled" Value="false"><Setter Property="Foreground" Value="#ADADAD"/><Setter Property="Background" Value="{DynamicResource DisabledBackgroundBrush}" TargetName="triangleButton"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter>

The firing of "HandleButtonClicked" from the main body of the button is where my inconsistencies lie.  There is a context menu as part of this button control, and the eventing from the "New Customer" button is behaving perfectly as normal. It's as if the style is getting in the way of the click event when it is applied to the main body of the button.

Anyone have any ideas?




The Generic.Xaml file in a VB.NET solution vs. a C# solution

$
0
0
We went to VS Live in Orlando, in December 2012. There Billy Hollis did an excellent presentation on WPF and navigation. We're trying to adapt his example app, which he did in VB.NET 2012, to C# 2012. He has a Generic.Xaml file in a folder named Themes in a project called NavShellCotrols. We have the same file (identical, in fact) in the same folder, in a project by the same name. When we run his example project in VS 2012, it works fine. But when we run our project, in VS 2012, it can't find the template named "HeaderContent" nor the one named "MainContent". I'm wondering if it has anything to do with the fact that they're different languages (VB.NET vs. C#)? I seem to remember that in VB.NET any files within folders in a project are treated as if they were all at the root level of the project; whereas with C# any files in folders in a project are treated differently. Not exactly like they're in different projects, but different nevertheless. Could that be why we're having difficulty?

Rod

Get control shape

$
0
0
Hello,

In WPF application I use external control. This control not support border but I want and border to this control. I think I can add border but I must know how I can get shape this control. Is possible Can I get shape this control?

Best regards,
Grzegorz Wiśniewski

General queries of new program with WPF

$
0
0
Hello forks,

This is Karl. First, I would like to introduce myself briefly to save our time. Actually, I am a new developer with .NET but I have worked at Software Company as a junior developer many of years. Especially I used to enjoy Java, EJB, C, C++ (not much), Flex, other RIA under Weblogic and another middleware and many of web programming languages such as PHP, JSP and etc. I mean I am not a novice programmer at all.

My new research lab has the software made by WPF, and now they looks forward to have new fancy one with a good visualization. The project was assigned to me. So I went thought WPF but someone told me WPF technology is obsolete like MFC and let find new technology for the software.

This is the reason why I am here and post this for hearing your comments and suggestions.

Is WPF still good for new project or do you recommend any others? Should I go with web? Which version of .NET should I use? Any comments are appreciated! 

Thanks in advance for your time and understanding my poor English.

Karl,
Viewing all 18858 articles
Browse latest View live


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