WPF 및 XAML의 숨겨진 기능?
다음은 다양한 언어에 대해 논의 된 수많은 숨겨진 기능입니다. 이제 XAML 및 WPF의 숨겨진 기능에 대해 궁금합니다.
내가 찾은 것은 ListView의 헤더 클릭 이벤트입니다.
<ListView x:Name='lv'
Height="150"
GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler">
GridViewColumnHeader.Click 속성이 나열되지 않습니다.
지금까지 관련 기능 중 일부 :
또한보십시오:
- C #의 숨겨진 기능
- 파이썬의 숨겨진 기능
- ASP.NET의 숨겨진 기능
- Perl의 숨겨진 기능
- 자바의 숨겨진 기능
- VB.NET의 숨겨진 기능
- PHP의 숨겨진 기능
- 루비의 숨겨진 기능
- C의 숨겨진 기능
- 등등........
멀티 바인딩 (StringFormat과 결합) :
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}, {1}">
<Binding Path="LastName" />
<Binding Path="FirstName" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
특정 시나리오에서 바인딩 작업을 디버깅하는 PresentationTraceSources.TraceLevel 트릭도 있습니다. WindowsBase 어셈블리에서 System.Diagnostics 네임 스페이스를 참조하기 만하면됩니다.
xmlns:sd="clr-namespace:System.Diagnostics;assembly=WindowsBase"
바인딩 표현식에 다음을 추가하십시오.
<TextBlock Text="{Binding Message, sd:PresentationTraceSources.TraceLevel=High}" />
로그는 다음과 같습니다.
System.Windows.Data Warning: 52 : Created BindingExpression (hash=5923895) for Binding (hash=7588182)
System.Windows.Data Warning: 54 : Path: 'Message'
System.Windows.Data Warning: 56 : BindingExpression (hash=5923895): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=5923895): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=5923895): Attach to System.Windows.Controls.TextBlock.Text (hash=65248697)
System.Windows.Data Warning: 63 : BindingExpression (hash=5923895): Resolving source
3.5sp1은 TargetNullValue를 바인딩에 도입했습니다. 값이 입력되면 바운드 속성이 Null로 설정되고 속성이 Null이면이 값이 표시됩니다.
<TextBox Text="{Binding Total, TargetNullValue=$0.00}" />
3.5sp1은 StringFormat을 바인딩 표현식에 도입했습니다. 예 :
<TextBox Text="{Binding Date, StringFormat='{}{0:MM/dd/yyyy}'}" />
때로는 레이블에 표시하기에 너무 긴 문자열이 나타납니다. 이 경우 타원을 표시 하는 TextTrimming
속성을 사용할 수 있습니다TextBlock
<TextBlock
Name="sampleTextBlock"
TextTrimming="WordEllipsis"
TextWrapping="NoWrap"/>
창에 에어로 효과 추가
<Window.Resources>
<ResourceDictionary Source="/PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" />
</Window.Resources>
x : TypeArguments를 사용하는 XAML의 제네릭
XAML에서 ObservableCollection을 사용하려면 XAML에서 선언 할 수 없으므로 ObservableCollection에서 파생되는 형식을 만들어야합니다. XAML 2009에서는 x : TypeArguments 특성을 사용하여 일반 유형의 유형을 정의 할 수 있습니다.
<!-- XAML 2006 -->
class EmployeeCollection : ObservableCollection<Employee>
{
}
<l:EmployeeCollection>
<l:Employee FirstName="John" Name="Doe" />
<l:Employee FirstName="Tim" Name="Smith" />
</lEmployeeCollection>
<!-- XAML 2009 -->
<ObservableCollection x:TypeArguments="Employee">
<l:Employee FirstName="John" Name="Doe" />
<l:Employee FirstName="Tim" Name="Smith" />
</ObservableCollection />
비활성화 된 컨트롤에 툴팁 표시
Wpf를 사용하면 비활성화 된 상태 인 경우 컨트롤에 도구 설명을 표시 할 수 있습니다.
예를 들어
<Button Content="Disabled Button" ToolTipService.ShowOnDisabled="True" IsEnabled="False" ToolTip="This is a disabled button"/>
x : Arguments와 함께 기본이 아닌 생성자 사용
XAML 2006에서 개체를 사용하려면 공개 기본 생성자가 있어야합니다. XAML 2009에서는 x : Arguments 구문을 사용하여 생성자 인수를 전달할 수 있습니다.
<!-- XAML 2006 -->
<DateTime>00:00:00.0000100</DateTime>
<!-- XAML 2009 -->
<DateTime>
<x:Arguments>
<x:Int64>100</x:Int64>
</x:Arguments>
</DateTime>
실제로 숨겨진 기능은 아니지만 WPF / XAML을 통해 Bea Stollnitz 와 Josh Smith 를 얻을 수 있습니다. WPF / XAML 프로그래밍의 여왕과 왕.
태그 확장 및 첨부 된 속성은 내가 가장 좋아하는 기능으로, XAML "어휘"를 매우 우아한 방식으로 확장 할 수 있습니다.
태그 확장
<!-- Binding to app settings -->
<CheckBox IsChecked="{my:SettingBinding MinimizeToTray}">Close to tray</CheckBox>
<!-- Fill ItemsControl with the values of an enum -->
<ComboBox ItemsSource="{my:EnumValues sys:DaysOfWeek}"/>
<!-- Localization -->
<TextBlock Text="{my:Localize HelloWorld.Text}"/>
<!-- Switch on the result of a binding -->
<TextBlock Text="{my:Switch Path=IsGood, ValueIfTrue=Good, ValueIfFalse=Bad}"/>
첨부 된 속성
<!-- Sort GridView automatically -->
<ListView ItemsSource="{Binding Persons}"
IsSynchronizedWithCurrentItem="True"
util:GridViewSort.AutoSort="True">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="Name"
DisplayMemberBinding="{Binding Name}"
util:GridViewSort.PropertyName="Name"/>
<GridViewColumn Header="First name"
DisplayMemberBinding="{Binding FirstName}"
util:GridViewSort.PropertyName="FirstName"/>
<GridViewColumn Header="Date of birth"
DisplayMemberBinding="{Binding DateOfBirth}"
util:GridViewSort.PropertyName="DateOfBirth"/>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
<!-- Vista Glass effect -->
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:WpfApplication1"
Title="Window1"
my:WinUtil.EnableAeroGlass="True">
...
GridViewSort 소스 (btw, GridViewColumnHeader.Click
Ortus에서 언급 한 이벤트를 사용함)
더하기 부호 ( +
)를 사용하여 XAML에서 중첩 유형을 참조 할 수 있습니다 . 예를 들어,이 클래스가 있다면 :
public class SomeClass
{
public enum SomeEnum
{
SomeValue
};
}
SomeValue
다음 구문을 사용하여 XAML에서 참조 할 수 있습니다.
{x:Static local:SomeClass+SomeEnum.SomeValue}
이 구문은 MSDN에 문서화되어 있지 않으며 공식적으로 지원되지 않습니다. 누군가 MSDN 포럼에서 그것에 대해 물었고 VS2010의 WPF Designer를 깨뜨린 것 같습니다. 그것은 한 보고 된 마이크로 소프트 연결에.
격자 크기 공유 ( 여기 에 좋은 예가 있습니다). 간단히 말해서 그리드 열과 행이 다른 그리드에서도 크기를 공유하도록 할 수 있습니다. 이것은 데이터를 제자리에 편집 할 필요없이 DataGrid를 사용하는 모든 사람들에게 매우 중요합니다.
PriorityBinding . "선착순"순서로 asyn 바인딩을 사용할 수 있습니다.
<TextBlock.Text>
<PriorityBinding FallbackValue="defaultvalue">
<Binding Path="SlowestDP" IsAsync="True"/>
<Binding Path="SlowerDP" IsAsync="True"/>
<Binding Path="FastDP" />
</PriorityBinding>
</TextBlock.Text>
x : FactoryMethod와 함께 정적 팩토리 메소드 사용
공용 생성자가 없지만 정적 팩토리 메서드가있는 형식이있는 경우 XAML 2006의 코드에서 해당 형식을 만들어야했습니다. XAML 2009에서는 x : FactoryMethodx : Arguments 특성을 사용하여 인수 값을 전달할 수 있습니다.
<!-- XAML 2006 -->
Guid id = Guid.NewGuid();
<!-- XAML 2009 -->
<Guid x:FactoryMethod="Guid.NewGuid" />
고급 "캡션"속성
명확하지 않은 또 다른 사항은 텍스트 만 포함하는 데 사용되는 일부 속성의 내용입니다. GUI 요소의 속성이 Object 유형 인 경우 텍스트를 설정하는 대신 컨트롤 집합이 포함 된 필요한 패널을 추가 할 수 있습니다.
이에 대한 예는 MenuItem입니다. 여기서 Header
속성 (일반적으로 텍스트 만 포함)에는 패널 컨트롤에 래핑 된 gui 요소 세트 (또는 필요한 경우 하나의 gui 요소)가 포함될 수 있습니다.
Icon
MenuItem 의 속성 도 참고하십시오 . 여기에는 일반적으로 Image 요소가 포함되지만 아무 것도 포함 할 수 있습니다!
<MenuItem Name="MyMenuItem" Click="MyMenuItem_Click">
<MenuItem.Icon>
<Button Click="Button1_Click">i</Button>
</MenuItem.Icon>
<MenuItem.Header>
<StackPanel Orientation="Horizontal" >
<Label>My text</Label>
<Button Click="Button2_Click">ClickMe!</Button>
</StackPanel>
</MenuItem.Header>
</MenuItem>
XAML 변환기
다음 목록은 WPF 커뮤니티에서 다른 형식을 XAML로 또는 그 반대로 변환하기 위해 개발 한 변환기를 보여줍니다.
Adobe Illustrator XAML 내보내기 플러그인
내장 타입
string 또는 double과 같은 간단한 유형의 객체를 오늘 리소스 사전에 추가하려면 필요한 clr-namespaces를 XML 네임 스페이스에 매핑해야합니다. XAML 2009에서는 XAML 언어에 포함 된 많은 간단한 유형이 있습니다.
<!-- XAML 2006 -->
<sys:String xmlns:sys="clr-namespace:System;assembly=mscorlib >Test</sys:String>
<!-- XAML 2009 -->
<x:String>Test</x:String>
XAML 언어에는 다음 유형이 포함됩니다.
<x:Object/>
<x:Boolean/>
<x:Char/>
<x:String/>
<x:Decimal/>
<x:Single/>
<x:Double/>
<x:Int16/>
<x:Int32/>
<x:Int64/>
<x:TimeSpan/>
<x:Uri/>
<x:Byte/>
<x:Array/>
<x:List/>
<x:Dictionary/>
{x : Reference}를 사용한 손쉬운 객체 참조
오늘 객체 참조를 생성하려면 데이터 바인딩을 수행하고 ElementName으로 소스를 선언해야합니다. XAML 2009에서는 새로운 {x : Reference} 태그 확장을 사용할 수 있습니다
<!-- XAML 2006 -->
<Label Target="{Binding ElementName=firstName}">FirstName</Label>
<TextBox x:Name="firstName" />
<!-- XAML 2009 -->
<Label Target="{x:Reference firstName}">FirstName</Label>
<TextBox x:Name="firstName" />
시스템 색상 사용법
<Border Background="{DynamicResource {x:Static SystemColors.InactiveBorderBrushKey}}"/>
임의 사전 키 지원
In XAML 2006 all explicit x:Key value were treated as strings. In XAML 2009 you can define any type of key you like by writing the key in ElementSyntax.
<!-- XAML 2006 -->
<StreamGeometry x:Key="CheckGeometry">M 0 0 L 12 8 l 9 12 z</StreamGeometry>
<!-- XAML 2009 -->
<StreamGeometry>M 0 0 L 12 8 l 9 12 z
<x:Key><x:Double>10.0</x:Double></x:Key>
</StreamGeometry>
Set a ValidationError by Code
A ValidatioRule in a BindingExpression only triggers, when the target side of the binding changes. If you want to set a validation error by code you can use the following snippet.
Set the validation error
ValidationError validationError =
new ValidationError(regexValidationRule,
textBox.GetBindingExpression(TextBox.TextProperty));
validationError.ErrorContent = "This is not a valid e-mail address";
Validation.MarkInvalid(
textBox.GetBindingExpression(TextBox.TextProperty),
validationError);
Clear the validation error
Validation.ClearInvalid(textBox.GetBindingExpression(TextBox.TextProperty));
The Ability to Stuff UIElement(s) into a TextBlock
I don't know how useful (it qualifies as hidden though) this is ... but it sure caught me off-guard when I first ran into it:
<Grid x:Name="LayoutRoot">
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid>
<Rectangle Fill="AliceBlue" Width="25" Height="25"/>
</Grid>
</TextBlock>
</Grid>
You could argue the following xaml could be useful (i.e. putting a graphic at the end of some text):
<Grid>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="Hello World">
<TextBlock.Resources>
<DrawingBrush x:Key="exclamationPoint" Stretch="Uniform">
<DrawingBrush.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="#FF375CE2" Geometry="F1 M 7.968,58.164L 0,58.164L 1.914,49.921L 9.882,49.921L 7.968,58.164 Z M 21.796,0L 11.054,42.148L 4.403,42.148L 13.049,0L 21.796,0 Z "/>
</DrawingGroup.Children>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</TextBlock.Resources>
<Grid>
<Rectangle Width="100" Height="100" Fill="{StaticResource exclamationPoint}"/>
</Grid>
</TextBlock>
</Grid>
The above xaml renders like the following:
Debugging Animations
Common Errors
If you get the following error: Cannot animate '(0).(1)' on an immutable object instance. it could be that you are run into one of the following limitations:
- You are animating a dependency property without setting a local value
- You are animating a dependency property who's current value is defined in another assembly that is not merged into the resource dictionary.
- You are animating a value that is currently databound
Binding without INotifyPropertyChanged or DependencyProperties
As discussed here you can bind a plain CLR object property without INotifyPropertyChanged, and it will just work.
Here is the Forumpost i am referring to.
Quote:
[...] WPF's data binding engine will data bind to PropertyDescriptor instance which wraps the source property if the source object is a plain CLR object and doesn't implement INotifyPropertyChanged interface. And the data binding engine will try to subscribe to the property changed event through PropertyDescriptor.AddValueChanged() method. And when the target data bound element change the property values, data binding engine will call PropertyDescriptor.SetValue() method to transfer the changed value back to the source property, and it will simultaneously raise ValueChanged event to notify other subscribers (in this instance, the other subscribers will be the TextBlocks within the ListBox.
And if you are implementing INotifyPropertyChanged, you are fully responsible to implement the change notification in every setter of the properties which needs to be data bound to the UI. Otherwise, the change will be not synchronized as you'd expect.[...]
Here is another great and detailed article on the subject.
Note this only works when using binding. If you update the values from code, the change won't be notified. [...]
Implementing INotifyPropertyChanged can be a fair bit of tedious development work. However, you'll need to weigh that work against the runtime footprint (memory and CPU) of your WPF application. Implementing INPC yourself will save runtime CPU and memory.
참고URL : https://stackoverflow.com/questions/1124769/hidden-features-of-wpf-and-xaml
'Programing' 카테고리의 다른 글
Bower ECMDERR 수정하는 방법 (0) | 2020.07.09 |
---|---|
XML 정의를 사용하여 삼각형 모양을 만드시겠습니까? (0) | 2020.07.09 |
오류 발생시 스크립트 종료 (0) | 2020.07.09 |
배열에서 속성 값을 합산하는 더 좋은 방법 (0) | 2020.07.09 |
대소 문자를 구분하지 않는 목록 검색 (0) | 2020.07.09 |