문제

나는 WPF를 처음 접했지만 여전히 XAML의 바인딩 주위에 머리를 감싸려고 노력하고 있습니다.

My.Settings의 String Collection 값으로 Combobox를 채우고 싶습니다. 다음과 같이 코드로 할 수 있습니다.

me.combobox1.itemssource = my.settings.mycollectionofstrings

... 그리고 그것은 작동합니다.

내 XAML에서 어떻게 할 수 있습니까? 가능합니까?

감사

도움이 되었습니까?

해결책

, 당신은 XAML에서 바인딩을 선언 할 수 있습니다. 왜냐하면 그것은 WPF에서 가장 강력한 기능 중 하나이기 때문입니다.

귀하의 경우 Combobox를 사용자 정의 설정 중 하나에 바인딩하려면 다음 XAML을 사용합니다.

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:p="clr-namespace:WpfApplication1.Properties"
    Title="Window1">
    <StackPanel>
        <ComboBox
            ItemsSource="{Binding Source={x:Static p:Settings.Default}, Path=MyCollectionOfStrings}" />
    </StackPanel>
</Window>

다음 측면을 주목하십시오.

  • 우리는 XAML에서 그것을 언급하기 위해 '설정'클래스가 존재하는 .NET 네임 스페이스를 가리키는 접두사 'p'가있는 XML 네임 스페이스를 선언했습니다.
  • XAML에서 바인딩을 선언하기 위해 마크 업 확장 '{binding}'을 사용했습니다.
  • 우리는 XAML의 정적 (VB의 '공유') 클래스 멤버를 참조하기 위해 마크 업 확장 '정적'을 사용했습니다.

다른 팁

사용자 정의 마크 업 확장을 사용하여 그렇게하기위한 더 간단한 솔루션이 있습니다. 귀하의 경우에는 다음과 같이 사용할 수 있습니다.

<Window x:Class="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" Height="90" Width="462" Name="Window1">
    <Grid>
        <ComboBox ItemsSource="{my:SettingBinding MyCollectionOfStrings}" />
    </Grid>
</Window>

내 블로그 에서이 마크 업 확장에 대한 C# 코드를 찾을 수 있습니다.http://www.thomaslevesque.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/

것이 가능하다. C#에서는 이렇게합니다 (간단한 bool) :

IsExpanded="{Binding Source={StaticResource Settings}, Mode=TwoWay, Path=Default.ASettingValue}"

내 app.xaml의 application.resources에서 정적 리소스 "설정"을 정의합니다.

<!-- other namespaces removed for clarity -->
<Application xmlns:settings="clr-namespace:DefaultNamespace.Properties" >
 <Application.Resources>
  <ResourceDictionary>
   <settings:Settings x:Key="Settings" />
   <!--stuff removed-->
  </ResourceDictionary>
 </Application.Resources>
</Application>

당신의 길은 다를 수 있습니다. C#에서는 응용 프로그램에서 앱 설정에 액세스 할 수 있습니다.

DefaultNamespace.Properties.Settings.Default.ASettingValue

알았어요!

<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:p="clr-namespace:WpfApplication1"
    Title="Window1" Height="90" Width="462" Name="Window1">
    <Grid>
        <ComboBox ItemsSource="{Binding Source={x:Static p:Settings.Default}, Path=MyCollectionOfStrings}" />
    </Grid>
</Window>

내가 위대한 "아하"에 도달하도록 도와 주셔서 감사합니다. 순간 :-) ... WPF에서 더 많은 시간을 보낸 후에 이것이 왜 효과가 있는지 이해할 것입니다.

목록을 설정에서 구분 된 문자열로 저장 한 다음 변환기를 사용 할 수도 있습니다.

<ComboBox ItemsSource="{Binding Default.ImportHistory,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay,Converter={StaticResource StringToListConverter},ConverterParameter=|}" IsEditable="True">
/// <summary>
/// Converts a delimited set of strings to a list and back again. The parameter defines the delimiter
/// </summary>
public class StringToListConverter : IValueConverter {
 /// <summary>
 /// Takes a string, returns a list seperated by {parameter}
 /// </summary>
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
     string serializedList = (value ?? string.Empty).ToString(),
            splitter = (parameter ?? string.Empty).ToString();
     if(serializedList.Trim().Length == 0) {
         return value;
     }
     return serializedList.Split(new[] { splitter }, StringSplitOptions.RemoveEmptyEntries);
 }
 /// <summary>
 /// Takes a list, returns a string seperated by {parameter}
 /// </summary>
 public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
     var items = value as IEnumerable;
     var splitter = (parameter ?? string.Empty).ToString();
     if(value == null || items == null) {
         return value;
     }
     StringBuilder buffer = new StringBuilder();
     foreach(var itm in items) {
         buffer.Append(itm.ToString()).Append(splitter);
     }
     return buffer.ToString(0, splitter.Length > 0 ? buffer.Length - splitter.Length : buffer.Length);
 }
}

그런 다음 찾아보기 버튼을 클릭하면 목록에 추가 할 수 있습니다.

var items = Settings.Default.ImportHistory.Split('|');
if(!items.Contains(dlgOpen.FileNames[0])) {
 Settings.Default.ImportHistory += ("|" + dlgOpen.FileNames[0]);
}
cboFilename.SelectedValue = dlgOpen.FileNames[0];
Settings.Default.Save();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top