我有一個文本框,它通過XAML綁定到一個列表框, 該文本框也綁定到一個視圖模型,多重綁定使用 來獲得這個,見下文。多重綁定,更好的解決方案?
想法是,在視圖模型中使用 之前,必須修改所選項目。
我對這段代碼並不滿意,對於這樣一個簡單的任務來說很複雜。 每個綁定都可以獨立完成。可以使用哪種簡單的方法 來選擇一個元素進行修改,並使用修改後的字符串進行視圖模型中的進一步處理 ?
--------------的XAML --------------
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:TheMultiValueConverter x:Key="theConverter"/>
</Window.Resources>
<StackPanel>
<TextBox Name="textBox">
<TextBox.Text>
<MultiBinding Converter="{StaticResource theConverter}" Mode="OneWay">
<Binding/>
<Binding ElementName="textBox" Path="Text"/>
<Binding ElementName="listBox" Path="SelectedItem" Mode="OneWay"/>
</MultiBinding>
</TextBox.Text>
</TextBox>
<ListBox Name="listBox" ItemsSource="{Binding Data}" />
</StackPanel>
</Window>
--------- -----視圖模型--------------
public class ViewModel : INotifyPropertyChanged
{
string modified;
public string Modified
{
get { return modified; }
set
{
if (modified != value)
{
modified = value;
NotifyPropertyChanged("Modified");
}
}
}
List<string> data = new List<string> { "Test1", "Test2" };
public List<string> Data
{
get { return data; }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
--------------值轉換器---- ----------
public class TheMultiValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var viewModel = values[0] as ViewModel;
if (viewModel != null)
{
viewModel.Modified = (string)values[1];
if (string.IsNullOrWhiteSpace(values[1].ToString()))
return values[2];
else
return values[1];
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
完美,感謝Gunter :) – Bertrand