Ответы пользователя Alexander - CodeHelper

Alexander

Alexander
Карма 1361
Имя Ояябу!
Возраст 27
Сайт Неизвестно
Twitter Неизвестно
Участвует в проекте 1111 дн., 23 час., 39 мин.
Последняя активность 502 дн., 6 час., 49 мин. назад
Ух какой!

Ответы

Новые Лучшие
1
2
3
4
5
Перейти к вопросу →

Вариант с DataTemplate

Имеем следующее описание для ListBox:

<ListBox Name="myListBox" ItemTemplate="{StaticResource myDataTemplate}"
         IsSynchronizedWithCurrentItem="True">
  <ListBox.ItemsSource>
    <Binding Source="{StaticResource InventoryData}" XPath="Books/Book"/>
  </ListBox.ItemsSource>
</ListBox>

описание используемого шаблона следующее:

<DataTemplate x:Key="myDataTemplate">
  <TextBlock Name="textBlock" FontSize="14" Foreground="Blue">
    <TextBlock.Text>
      <Binding XPath="Title"/>
    </TextBlock.Text>
  </TextBlock>
</DataTemplate>

тогда в runtime к данному текстовому блоку можно обратиться следующим образом:

// Getting the currently selected ListBoxItem
// Note that the ListBox must have
// IsSynchronizedWithCurrentItem set to True for this to work
ListBoxItem myListBoxItem =
    (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));

// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);

// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);

// Do something to the DataTemplate-generated TextBlock
MessageBox.Show("The text of the TextBlock of the selected list item: "
    + myTextBlock.Text);

Реализация метода FindVisualChild следующая:

private childItem FindVisualChild<childItem>(DependencyObject obj)
    where childItem : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);
        if (child != null && child is childItem)
            return (childItem)child;
        else
        {
            childItem childOfChild = FindVisualChild<childItem>(child);
            if (childOfChild != null)
                return childOfChild;
        }
    }
    return null;
}
Перейти к вопросу →

Вариант с ControlTemplate.

Имеем следующее описание стиля кнопки:

<Style TargetType="{x:Type Button}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Button}">
        <Grid Margin="5" Name="grid">
          <Ellipse Stroke="DarkBlue" StrokeThickness="2">
            <Ellipse.Fill>
              <RadialGradientBrush Center="0.3,0.2" RadiusX="0.5" RadiusY="0.5">
                <GradientStop Color="Azure" Offset="0.1" />
                <GradientStop Color="CornflowerBlue" Offset="1.1" />
              </RadialGradientBrush>
            </Ellipse.Fill>
          </Ellipse>
          <ContentPresenter Name="content" Margin="10"
                            HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

В таком случае к сетке внутри кнопки можно обратиться так:

// Finding the grid that is generated by the ControlTemplate of the Button
Grid gridInTemplate = (Grid)myButton1.Template.FindName("grid", myButton1);

// Do something to the ControlTemplate-generated grid
MessageBox.Show("The actual width of the grid in the ControlTemplate: "
    + gridInTemplate.GetValue(Grid.ActualWidthProperty).ToString());
Перейти к вопросу →

Причем обойтись одним поиском для вложенных шаблонов не получится.

Перейти к вопросу →

Посмотри вот это к примеру:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Xml Data Binding" FontSize="20"
    >
  <StackPanel Orientation="Horizontal">
    <StackPanel.Resources>
      <Style x:Key="{x:Type ListBoxItem}" TargetType="{x:Type ListBoxItem}">
        <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
              <Grid>
                <ContentPresenter />
                <TextBox Name="EditableText" Visibility="Collapsed"/>
              </Grid>
              <ControlTemplate.Triggers>
                <Trigger Property="IsSelected" Value="true">
                  <Setter TargetName="EditableText" Property="Visibility" Value="Visible" />
                  <Setter TargetName="EditableText" Property="Text" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}"/>
                </Trigger>
              </ControlTemplate.Triggers>
            </ControlTemplate>
          </Setter.Value>
        </Setter>
      </Style>
    </StackPanel.Resources>
    <ListBox Width="100" Height="155">
      <ListBoxItem>Item 1</ListBoxItem>
      <ListBoxItem>Item 2</ListBoxItem>
      <ListBoxItem>Item 3</ListBoxItem>
    </ListBox>
    <ListBox Width="100" Height="155">
      <ListBoxItem>Item 1</ListBoxItem>
      <ListBoxItem>Item 2</ListBoxItem>
      <ListBoxItem>Item 3</ListBoxItem>
    </ListBox>
  </StackPanel>
</Page>
Перейти к вопросу →

Вот посмотри. Вся фишка в ICollectionView по-моему, ну и реализации метода фильтрации.

Перейти к вопросу →

Sybase PowerDesigner - отличная вещь. На все случаи жизни + куча плагинов под разные цели. Правда платная. Или вот еще:

  1. Microsoft Visio. http://office.microsoft.com/en-us/FX010857981033.aspx
  2. Sparx Enterprise Architect Professional. http://www.sparxsystems.com.au
Перейти к вопросу →

Самое простое:

string path = @"бла-бла-бла дирректория";
FileInfo fi = new FileInfo(path);
if (fi.Exists){
   //значит файл
}
else{
   DirectoryIndo di = new DirectoryInfo(path);
   //аналогично
}
Перейти к вопросу →

Об OpenFileDialog в справке:

Most of the functionality for this class is found in the FileDialog class.

If you want to give the user the ability to select a folder instead of a file, use FolderBrowserDialog instead.

Перейти к вопросу →

Вот статья, рассказывающая о локализации WPF приложения. Там так же используется расширение разметки, при этом читабельность падает однозначно. Однако приведен пример использования локализуемых строк из кода.

Разметка выглядит примерно вот так:

    <TextBlock loc:Translate.Uid="3"
        Text="{loc:Translate}"
        Background="{loc:Translate}"
        Width="{loc:Translate}"
        Height="{loc:Translate}" FontSize="18" />

    <TextBlock FontSize="18">
        <TextBlock.Text>
            <loc:Translate>
                <Binding ElementName="Root" Path="Uid" />
            </loc:Translate>
        </TextBlock.Text>
    </TextBlock>

При этом в коде можно делать так:

LanguageDictionary dictionary = LanguageDictionary.GetDictionary(LanguageContext.Instance.Culture);    
string message = dictionary.Translate("NotEnoughMemory", "Message", typeof(string)) as string;

English Entry:

<Value Id="NotEnoughMemory" Message="There is not enough memory" />

Hebrew Entry:

<Value Id="NotEnoughMemory" Message="אין מספיק זכרון" />
Перейти к вопросу →

Вот еще один вариант локализации интерфейса WPF приложения. Здесь опять же ничего не говориться о динамически формируемых строках, но описание интерфейса вроде бы более наглядное + довольно легко в runtime можно сменить язык.

Разметка при таком подходе выглядит примерно вот так:

<Window.Resources>
  <XmlDataProvider x:Key="Lang" Source="/lng/german.xml" XPath="CrypTool"/>
  </Window.Resources>
  <Window.Background>
    ... 
  <TreeView Margin="10" FontSize="12" Name="Menu" 
    VerticalAlignment="Top" Grid.Column="0" Grid.Row="0" 
    Background="{x:Null}">
  <TreeViewItem Name="MenuItemDocSetup" Header="{Binding Source=
    {StaticResource Lang}, XPath=MenuItemDocSetup/@Header}" 
    Selected="DocSetup"/>
   ...

1
2
3
4
5
v1.7.123.556
© 2009—2010 CodeHelper FAQ | О сайте | Обратная связь | История изменений | Статьи
Creative Commons LicenseМатериалы сайта распространяются под лицензией Creative Commons Attribution-Share Alike 3.0 Unported.