Englisht etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Englisht etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

Perşembe, Mart 19, 2009

WPF AutoComplete Folder TextBox

Introduction

This article demos how to create a TextBox that can suggest items at runtime based on input, in this case, disk drive folders.

Background

There is a number of AutoComplete TextBox implementation around but some don't support data binding, others don't support runtime items polling and so on. After lot of research and Googling, I decided to write my own instead of continue looking for one.

My Design process

My first design is based on ComboBox, I copy the default template and remove the drop down button and develop from that, it doesnt work because combobox have it's own autocomplete mechanism which will change the selection of textbox when Items is changed, it's not designed for Items that change at realtime.

So the second design is based on TextBox, I create the following style :

<Style x:Key="autoCompleteTextBox" TargetType="{x:Type TextBox}"><Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBoxBase}"> <Grid x:Name="root"> <ScrollViewer Margin="0" x:Name="PART_ContentHost"/> <Popup x:Name="PART_Popup" AllowsTransparency="true"

Placement="Bottom" IsOpen="False" PopupAnimation="{DynamicResource

{x:Static SystemParameters.ComboBoxPopupAnimationKey}}"> <ListBox x:Name="PART_ItemList" SnapsToDevicePixels

="{TemplateBinding SnapsToDevicePixels}" VerticalContentAlignment="Stretch" HorizontalContentAlignment

="Stretch" KeyboardNavigation.DirectionalNavigation="Contained" /> </Popup> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>

and then create a custom control and hook the style to it :

<TextBox x:Class="QuickZip.Controls.SelectFolderTextBox" Style="{DynamicResource autoCompleteTextBox}" >...
</TextBox>

PART_ContentHost is actually a control that TextBoxView, it is required for TextBox template
(with that name), or the control won't function, the another two part (PART_Popup and PART_ItemList)
is defined so I can use them in the custom control :

public partial class SelectFolderTextBox : TextBox

{

Popup Popup { get { return this.Template.FindName("PART_Popup", this) as Popup; } }

ListBox ItemList { get { return this.Template.FindName("PART_ItemList", this) as ListBox; } }

ScrollViewer Host { get { return this.Template.FindName("PART_ContentHost", this) as ScrollViewer; } }

UIElement TextBoxView { get { foreach (object o in LogicalTreeHelper.GetChildren(Host)) return o as UIElement; return null; } }

}

AutoCompleteTextBox

If text is changed, the suggestion item list is updated as well :

protected override void OnTextChanged(TextChangedEventArgs e)

{

if (_loaded)

{

try

{

if (lastPath != Path.GetDirectoryName(this.Text))

{

lastPath = Path.GetDirectoryName(this.Text);

string[] paths = Lookup(this.Text);

ItemList.Items.Clear();

foreach (string path in paths)

if (!(String.Equals(path, this.Text, StringComparison.CurrentCultureIgnoreCase)))

ItemList.Items.Add(path);

}

Popup.IsOpen = true;

//I added a Filter so Directory polling is only called once per directory, thus improve speed

ItemList.Items.Filter = p =>

{

string path = p as string;

return path.StartsWith(this.Text, StringComparison.CurrentCultureIgnoreCase) &&

!(String.Equals(path, this.Text, StringComparison.CurrentCultureIgnoreCase));

};

}

catch

{

}

}

}

A number of handlers is then defined :

public override void OnApplyTemplate()

{

base.OnApplyTemplate();

_loaded = true;

this.KeyDown += new KeyEventHandler(AutoCompleteTextBox_KeyDown);

this.PreviewKeyDown += new KeyEventHandler(AutoCompleteTextBox_PreviewKeyDown);

ItemList.PreviewMouseDown += new MouseButtonEventHandler(ItemList_PreviewMouseDown);

ItemList.KeyDown += new KeyEventHandler(ItemList_KeyDown);

}

AutoCompleteTextBox_PreviewKeyDown :

if user press down button, the textbox will move focus to the Listbox, so the user can choose an item from it, this is placed in PreviewKeyDown instead of KeyDown because TextBox's mechanism will consume the event before it reach KeyDown if the button is down button.

void AutoCompleteTextBox_PreviewKeyDown(object sender, KeyEventArgs e)

{

if (e.Key == Key.Down && ItemList.Items.Count > 0 && !(e.OriginalSource is ListBoxItem))

{

ItemList.Focus();

ItemList.SelectedIndex = 0;

ListBoxItem lbi = ItemList.ItemContainerGenerator.ContainerFromIndex(ItemList.SelectedIndex) as ListBoxItem;

lbi.Focus();

e.Handled = true;

}

}

AutoCompleteTextBox_KeyDown

if user press <enter> button, the textbox will close the popup and update the binding.

void AutoCompleteTextBox_KeyDown(object sender, KeyEventArgs e)

{

if (e.Key == Key.Enter)

{

Popup.IsOpen = false;

updateSource();

}

}

ItemList_PreviewMouseDown and ItemList_PreviewMouseDown

if user press <enter> button (or select by mouse), the text textbox will be updated with ListBox.SelectedValue, and then update the binding.

void ItemList_KeyDown(object sender, KeyEventArgs e)

{

if (e.OriginalSource is ListBoxItem)

{

ListBoxItem tb = e.OriginalSource as ListBoxItem;

Text = (tb.Content as string);

if (e.Key == Key.Enter)

{

Popup.IsOpen = false;

updateSource();

}

}

}

void ItemList_PreviewMouseDown(object sender, MouseButtonEventArgs e)

{

if (e.LeftButton == MouseButtonState.Pressed)

{

{

TextBlock tb = e.OriginalSource as TextBlock;

if (tb != null)

{

Text = tb.Text;

updateSource();

Popup.IsOpen = false;

e.Handled = true;

}

}

}

updateSource is required because I bound text's UpdateSourceTrigger as Explicit, if updateSource is not called it wont update the text :

void updateSource()

{

if (this.GetBindingExpression(TextBox.TextProperty) != null)

this.GetBindingExpression(TextBox.TextProperty).UpdateSource();

}

The component is working now, but if you want to add validation as well, read below :

To support validation, a Validation Rule is written :

If the path is not found or an exception raised when looking up, it will return ValidationResult false, the error will be

accessed by using the attached properties Validation.Errors and Validation.HasError.

public class DirectoryExistsRule : ValidationRule

{

public static DirectoryExistsRule Instance = new DirectoryExistsRule();

public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)

{

try

{

if (!(value is string))

return new ValidationResult(false, "InvalidPath");

if (!Directory.Exists((string)value))

return new ValidationResult(false, "Path Not Found");

}

catch (Exception ex)

{

return new ValidationResult(false, "Invalid Path");

}

return new ValidationResult(true, null);

}

}

and change the binding : (to use the created Validation rule, noted that UpdateSourceTrigger is Explicit. )

<local:SelectFolderTextBox x:Name="stb" DockPanel.Dock="Bottom" Margin="4,0,0,0">

<local:SelectFolderTextBox.Text>

<Binding Path="Text" UpdateSourceTrigger="Explicit" >

<Binding.ValidationRules>

<t:DirectoryExistsRule />

</Binding.ValidationRules>

</Binding>

</local:SelectFolderTextBox.Text>

</local:SelectFolderTextBox>

Now the textbox show a red border if directory not exists. As a red border isnt clear enough, we can change the behavior :

to disable the default red border:

<Style x:Key="autoCompleteTextBox" TargetType="{x:Type TextBox}">

<...>

<Setter Property="Validation.ErrorTemplate">

<Setter.Value>

<ControlTemplate >

<AdornedElementPlaceholder />

<!-- The TextBox Element -->

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

then change the control template, which will show the dockWarning when Validation.HasError :

<ControlTemplate TargetType="{x:Type TextBoxBase}">

<Border Name="Border" CornerRadius="2" Background="{StaticResource WindowBackgroundBrush}"

BorderBrush="{StaticResource SolidBorderBrush}" BorderThickness="1" Padding="1" >

<Grid x:Name="root">

<...>

<DockPanel x:Name="dockWarning" Visibility="Collapsed" LastChildFill="False" >

<Border DockPanel.Dock="Right" BorderBrush="Red" Background="Red" BorderThickness="2" CornerRadius="2,2,0,0">

<TextBlock x:Name="txtWarning" DockPanel.Dock="Right" Text="{TemplateBinding ToolTip}" VerticalAlignment="Top"

Background="Red" Foreground="White" FontSize="10" />

<Border.RenderTransform>

<TranslateTransform X="2" Y="{Binding ElementName=dockWarning, Path=ActualHeight,

Converter={x:Static t:InvertSignConverter.Instance}}"/>

<!--TranslateTransform move the border to upper right corner, outside the TextBox -->

<!--InvertSignConverter is a IValueConverter that change + to -, - to + -->

</Border.RenderTransform>

</Border>

</DockPanel>

</Grid>

</Border>

<ControlTemplate.Triggers>

<MultiTrigger>

<MultiTrigger.Conditions>

<Condition Property="Validation.HasError" Value="true" />

<Condition SourceName="PART_Popup" Property="IsOpen" Value="False" />

</MultiTrigger.Conditions>

<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>

<Setter TargetName="dockWarning" Property="Visibility" Value="Visible" />

<Setter TargetName="Border" Property="BorderThickness" Value="2" />

<Setter TargetName="Border" Property="Padding" Value="0" />

<Setter TargetName="Border" Property="BorderBrush" Value="Red" />

</MultiTrigger>

</ControlTemplate.Triggers>

</ControlTemplate>

Cumartesi, Ağustos 09, 2008

Silverlight Blueprint for Sharepoint

Did you ever want to integrated Silverlight with SharePoint? Check out the brand new Silverlight Blueprint for SharePoint site:http://www.ssblueprints.net/sharepoint/ !

At U2U we've created the six samples of the Blueprint that illustrate the integration options. You can read more details on Patrick's blog and Karine's blog (she posted some screenshots). The Blueprint will also be announced by Bill Gates during the SharePoint Conference keynote later today, the SharePoint team blogged

Cuma, Haziran 20, 2008

Free Silverlight Datagrid from DevExpress

header_top

The folks at DevExpress are releasing a FREE DataGrid for Silverlight.

Here are come of the features.....

  • Data Grouping against multiple Silverlight Grid columns
  • Data Sorting against multiple Silverlight Grid columns
  • Comprehensive Summary Computation support against multiple Silverlight Grid columns
  • Column Movement
  • Column Resizing
  • Column Auto-Width
  • Row Editing
  • Row Preview (with animation)
  • Template Support (for cell content, cell editing, row preview and headers)
  • Auto Height Support for cells, headers, and totals.
  • Virtual StackPanel Row Container (simply means we are able to handle an unlimited number of rows)
  • Focused Row and Focused Cell
  • Multi-Row Selection Cell Text Wrapping
  • Vertical/Horizontal Lines
  • Multiple column types/editors

Click here for more info

Cumartesi, Nisan 26, 2008

Configuring a Web Server to Host Silverlight Content

Deploying Silverlight content to a production web server is a pretty easy process. Despite occasional misconception, Silverlight doesn't require a Microsoft-based web server: Apache can host up Silverlight content just as happily as IIS.

But there's one little gotcha: web servers are typically configured to only serve up a limited set of known file extensions as static content. That's all well and good, but Silverlight introduces two new file extensions (.xaml for loose XAML files and .xap for the zip-based binary packaging format). As a result, you need to add the MIME types for those file extensions to your web server so that it recognizes Silverlight content appropriately. Here are the MIME types you need to add to the server configuration:

Extension - MIME Type

.xaml - application/xaml+xml

.xap - application/x-silverlight-app

That's all you have to do. Unfortunately, it's not possible to provide generic instructions for how to add MIME types, as it varies from server to server, but here are some links for various common web servers:

While you're updating the list of MIME types served, you might want to also add the relevant types to your web server to support WPF and ClickOnce applications. Here are the additional items you'll need:

Extension - MIME Type

.manifest - application/manifest

.application - application/x-ms-application

.xbap - application/x-ms-xbap

.deploy - application/octet-stream

.xps - application/vnd.ms-xpsdocument

But what if you're hosting your Silverlight application on a shared hosting service and your hoster doesn't give you access to change these settings? The good news is that there are two options available to you. Obviously, you could take advantage of Silverlight Streaming, our free hosting service for up to 10GB of Silverlight content.

Alternatively, you can "cheat" the web server by renaming the XAP file extension to a compatible MIME type. The XAP container is ZIP-based, so you can simply rename the output file from .xap to .zip and change the source param within the object tag contained in the HTML file to point to the new file location. Click on this hyperlink to see the technique in action - it's a plain HTML file that points to a ZIP file (containing the Silverlight content).

One last piece of good news: IIS 7, included in Windows Server 2008, already includes all the relevant MIME types for both WPF and Silverlight, including both .xap and .xaml extensions, so if you're using Windows Server 2008, you're all set. (The same applies to a clean install of Windows Vista SP1, although if you upgrade from the RTM to the SP1 release, your settings will remain unchanged until you uninstall and reinstall the IIS feature).

Perşembe, Mart 20, 2008

Windows Vista SP1

Merhabalar

Uzun zamandır beklenen Vista SP1 sonunda çıktı. Vista SP1 ile sistemimizin performansı iyileştiriliyor ve güvenlik açıklarıda düzeltiliyor. Özellikle de bir dvd 'yi 60 dakika yerine 2 dakika da kopyalayabilmek çok güzel bir duygu oldu. :)

Fakat hardiskiniz de 4GB 'dan az boş yer varsa maalesef kuramıyorsunuz. Bu ufak notuda belirtmek isterim...

Sizlerinde bu güncelleştirmeyi yüklemenizi öneriyorum.

Windows Vista Update ile gelen görünümü,

Vista sp1

Direk indirerek arşivlemek isteyenler için linki,

http://www.microsoft.com/downloads/details.aspx?FamilyID=b0c7136d-5ebb-413b-89c9-cb3d06d12674&DisplayLang=en

Herkese iyi çalışmalar...

Pazartesi, Mart 17, 2008

Expression Web 2.0 News

What's new in Expression Web 2.0 ?
PHP
Open up your PHP websites to the visual world of standards-based design by using advanced code editing features and effortless browser previewing. Microsoft Expression Web 2 enables you to preview PHP pages in your web browser without installing a separate development server or having to upload your website to a server. Just click the Preview in Browser button and you're done. Code view provides customizable color coding to help you identify the different components in your PHP syntax, and also provides PHP IntelliSense (auto complete), which lets you quickly look up and insert code. PHP IntelliSense options let you control the amount of IntelliSense that is provided. You can efficiently insert common PHP code snippets in eitherDesign view or Code view from the Insert menu. When you want to reuse content on multiple PHP pages, such as for a header or navigation menu, you can use a PHP include and preview it in Design view. Formatting marks in Design view identify your PHP script and enable you to modify the script outside Code view.
Byte order mark options
When you're designing documents encoded as Unicode UTF-8, a byte order mark (BOM) is typically a good thing to have embedded in your documents. But if you're working with PHP pages, or use a server or other tools that do not support a BOM, an embedded BOM can cause unwanted characters to appear in your document, or can create other issues. Expression Web 2 lets you add or remove a BOM in existing documents, and control whether a BOM is added to new documents.
Silverlight 1.0
Microsoft Silverlight is a cross-browser, cross–platform plug-in for delivering rich interactive applications for the web. You can use Expression Web 2 to either modify the HTML file that was generated by your Silverlight-authoring program or insert a Silverlight-based application into a web page.
Flash and Windows Media
Expression Web 2 lets you insert Flash SWF and Windows Media files into your pages, edit their properties, and preview your Flash files in Design view. In addition, you can insert and run any other type of ActiveX control, such as QuickTime or RealPlayer.
Photoshop Import
Expression Web 2 enables you to generate a .png, .gif, or .jpeg file from a Photoshop .psd file and select the Photoshop layers you want to include or exclude from the image. After using Expression Web 2 to generate a web-optimized image, you can quickly start Adobe Photoshop to modify the original .psd file and then update the image that you generated with Expression Web.
ASP.NET AJAX
Expression Web 2 provides you with ASP.NET AJAX server controls that enable you to quickly create web pages that include a rich user experience with responsive and familiar user interface (UI) elements. By using AJAX features, you can improve the user experience with web pages that are richer, that are more responsive to user actions, and that behave like traditional client applications.
ASP.NET AJAX server controls supported by Expression Web 2 include the UpdatePanel, Timer, UpdateProgress, ScriptManager, and ScriptManagerProxy controls.

Note To work with these controls in Expression Web 2, you must install ASP.NET AJAX or the .NET Framework 3.5. See Microsoft .NET Framework 3.5 or ASP.NET AJAX 1.0 in the Microsoft Download Center online.
Custom ASP.NET controls
Expression Web 2 supports custom ASP.NET controls that you have put in the BIN folder of your website. You can preview custom controls and access the Common Tasks smart tag menu in Design view, edit properties, and use IntelliSense and syntax checking in Code view.
You can use custom ASP.NET controls developed by others, such as those featured in theControl Gallery on the Microsoft ASP.NET website, or create custom controls by using a visual design tool such as Microsoft Visual Studio.

ASP.NET data controls
Expression Web 2 provides the new DataPager and ListView ASP.NET controls. The ListView control is useful for displaying data in any repeating structure, similar to the DataList and Repeater controls. Unlike those controls, the ListView control supports edit, insert, and delete operations, and also sorting and paging. You use the DataPager control to enable users to page through data in a ListView control.
Note To work with these controls in Expression Web 2, you must install the .NET Framework 3.5. See Microsoft .NET Framework 3.5 in the Microsoft Download Center online.
FTP publishing
Expression Web 2 enables you to set the FTP publishing mode to Passive FTP or normal FTP, and save your FTP user name and password.
CSS
The Design view in Expression Web 2 now renders the CSS overflow property. The Compatibility Reports in Expression Web 2 now check external CSS files, in addition to embedded style sheets, for compatibility with the CSS schema you specify.
HTML file extension
Expression Web 2 lets you set your preference for the default HTML file name extension.
Alphabetized HTML attributes
A new setting in the Code Formatting options in the Page Editor Options dialog box enables you to control whether HTML attributes are alphabetized or not in the code of your web pages. By default, tag attributes are now written in alphabetical order when Expression Web 2 adds HTML tags to your page. Existing tags in a page are affected by the new setting only if you apply the Reformat HTML command to the page.